复制到目标时,Copy-Item会收到IOException

时间:2017-01-23 21:19:40

标签: powershell

Copy-Item将文件复制到目标时,即使目标是干净的,我也会收到IOException。意味着在复制过程之前目标中没有文件。奇怪的是,它不会抛出所有文件的错误,并且复制时遇到问题的文件会被复制。如果它不起作用我会更容易。

用于执行复制的代码以这样的方式执行,即它在目标位置创建源路径的当前目录结构。

Get-ChildItem $SourcePath -Recurse -Include "$FilePattern" | Foreach-Object {
    $destDir = Split-Path ($_.FullName -replace [regex]::Escape($SourcePath), $dstfolder)
    if (!(Test-Path $destDir)) {
        New-Item -ItemType directory $destDir -ErrorAction SilentlyContinue | Out-Null
        sleep 1
    }
    Copy-Item $_ -Destination $destDir -Force -ErrorAction Ignore -Verbose | Write-Output
}

实际的错误消息是

VERBOSE: Performing operation "Copy File" on Target "Item: \\EPM111242ND\C$\
HypStaging\Objects\Applications\Vision\Plan1\Plan1.otl Destination:
C:\Users\epmadmin\Documents\Backups\Monday\Full\Objects\Applications\Vision\
Plan1\Plan1.otl". The process cannot access the file 'C:\Users\epmadmin\
Documents\Backups\Monday\Full\Objects\Applications\Visio n\Plan1\Plan1.otl'
because it is being used by another process.
    + CategoryInfo          : NotSpecified: (:) [Copy-Item],   IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
    + PSComputerName        : localhost

它似乎是目标文件,它有一个问题,在复制之前它不存在。奇怪的是,当我检查它时,文件就在那里。所以我尝试了-ErrorAction SilentlyContinue-Ignore,两者仍然会产生错误消息。我想到可能会尝试使用catch语句,但我不确定是否会抑制该消息。

1 个答案:

答案 0 :(得分:-1)

试试这个

Get-ChildItem $SourcePath -Recurse -Include "$FilePattern" | % {
$destDir = Split-Path ($_.FullName -replace [regex]::Escape($SourcePath), $dstfolder);
New-Item -ItemType directory $destDir -Force;
Copy-Item $_.fullname -Destination $destDir -Force
}