【问题标题】:Copy-Item gets IOException when copying to the destinationCopy-Item 在复制到目标时获取 IOException
【发布时间】:2017-01-24 15:16:50
【问题描述】:

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
}

实际的错误信息是

详细:对目标“项目:\\EPM111242ND\C$\ 执行“复制文件”操作
HypStaging\Objects\Applications\Vision\Plan1\Plan1.otl 目的地:
C:\Users\epmadmin\Documents\Backups\Monday\Full\Objects\Applications\Vision\
Plan1\Plan1.otl"。进程无法访问文件 'C:\Users\epmadmin\
Documents\Backups\Monday\Full\Objects\Applications\Visio n\Plan1\Plan1.otl'
因为它正在被另一个进程使用。
    + CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
    + PSComputerName : 本地主机

这似乎是它存在问题的目标文件,直到它被复制后才存在。奇怪的是,当我检查它时,文件就在那里。所以我尝试了-ErrorAction SilentlyContinue-Ignore 并且都仍然产生错误信息。我考虑过可能会添加一个 try catch 语句,但我不确定这会抑制消息。

【问题讨论】:

  • 不能那样工作。如果另一个进程锁定了一个文件,您不能通过-ErrorAction-Ignore 强制释放该锁。找到打开文件的进程并让它关闭文件。识别过程的合适工具是handleProcess Explorer
  • 看到我最初认为还有一些外部进程试图查看文件,例如 AV 扫描仪或其他东西,但我排除了目标目录,我仍然收到消息。解决它的唯一方法是在复制项周围放置一个 try-catch 语句,然后我没有收到“出于明显原因”的消息
  • @todd1215 出于好奇,Copy-Item 运行时的当前工作目录是什么?您可以通过Get-Location$PWD/ 找到它
  • 目录位置是用户Documents目录C:\Users\epmadmin\Documents

标签: powershell


【解决方案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
}

【讨论】:

  • 试着把 () 像这样 (Get-ChildItem $SourcePath -Recurse -Include "$FilePattern" ) | .........
猜你喜欢
  • 1970-01-01
  • 2014-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-11
  • 2017-12-04
  • 2012-08-26
相关资源
最近更新 更多