我正在尝试编写一种脚本解决方案,将某些文件从一个位置复制到另一个位置。
我有一个.csv格式的文件列表,带有标题
"ParentFolder, Name, FullName, lastwritetime."
文件内容为,具有数百行,并且路径不同,但是驱动器号相同:
"X:\clients\A90\201AA3.05\","2012.08 RAP Proposal.xlsm","X:\clients\A90\201AA3.05\2012.08 RAP Proposal.xlsm","20/05/2016 10:41:08"
我想做的是复制上面的..
"X:\clients\A90\201AA3.05\2012.08 RAP Proposal.xlsm"
到具有differentnet驱动器但目录结构相同的新位置。因此,在csv文件中,我具有文件名和路径,但是不确定如何从那里拆分驱动器并进行变量设置。我有一个foreach循环。
$ToCopy = Import-Csv "c:\temp\log.csv"
foreach($Line in $ToCopy)
{
$FullPath = $Line.ParentFolder
$File = $Line.Name
$FullName = $Line.FullName
$file = "$FullPath\$FullName"
$DestPath = Split-Path $FullPath -NoQualifier
Copy-Item "$FullName" -Destination c:\test\$DestPath
}
我收到的错误消息是:
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
Copy-Item : Could not find a part of the path 'C:\test\clients\A90\Support\_index0901\'.
At line:9 char:9
+ Copy-Item "$FullName" -Destination c:\test\$DestPath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Copy-Item], DirectoryNotFoundException
+ FullyQualifiedErrorId : System.IO.DirectoryNotFoundException,Microsoft.PowerShell.Commands.CopyItemCommand
最佳答案
您需要先创建文件夹,然后再尝试在其中复制文件。
这是一种简化方法,与已有的方法相比有所简化,但是增加了一行内容来处理文件夹的创建。
foreach($File in $ToCopy)
{
$DestPath = Join-Path -Path 'c:\test' -ChildPath ( Split-Path $File.ParentFolder -NoQualifier )
If ( -not ( Test-Path -Path $DestPath ) ) { New-Item -Path $DestPath -Force -ItemType Directory }
Copy-Item $File.FullName -Destination $DestPath -WhatIf
}
(注意,我将迭代变量从$ Line更改为$ File)
关于powershell - 脚本中的错误消息,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39410880/