【问题标题】:Powershell Move-Item works but shows error "the process cannot access the file because it is being used by another process'Powershell Move-Item 工作但显示错误“该进程无法访问该文件,因为它正被另一个进程使用”
【发布时间】:2022-11-22 10:15:51
【问题描述】:

我有一个运行以下脚本的 powershell 脚本,它成功地将我的文件和文件夹从当前文件夹移动到目标文件夹。但是它显示错误“该进程无法访问该文件,因为它正被另一个进程使用”

我的脚本:

mkdir filestobehere
$dest = '.\filestobehere'
Move-Item .\* $dest -Exclude $dest -Force
I am stumped.

我试图尝试捕获,但它没有被捕获,我仍然收到错误。

mkdir filestobehere
Get-ChildItem -Path "./" |
ForEach-Object {
  $dest = '.\filestobehere'
  Try {
    Move-Item .\* $dest -Exclude $dest -Force
  }
  Catch {
    Write-Hose "File is in use"
  }
}

【问题讨论】:

  • Move-Item:Exclude参数仅在命令包含某项内容时有效,例如C:\Windows\*,其中通配符指定C:\Windows目录的内容。
  • @Theo 我想我可以使用 Exclude 因为我的源路径是 .* 也就是我当前目录的内容
  • 不,您将 Exclude 设置为文字字符串 '.\filestobehere'
  • @Theo 我将 ErrorAction Stop 附加到 Move-Item,它现在打印“文件正在使用”。但是,如果我写 'Write-Host "File $($_.FullName) is in use",我想知道为什么它不写文件名?
  • 那是因为在你的 Catch 块中你没有显示真实的错误,只是您自己的文本"File is in use".. 将其更改为$_.Exception.Message。您是否阅读了我关于 -Exclude 开关的第一条评论?它不适用于文件路径,仅适用于文件名..

标签: powershell file


【解决方案1】:

正如 cmets 中所述,您尝试的主要问题是你正在使用小路作为不支持的 -Exclude 参数.

结果,排除尝试无效,并且 Move-Item 尝试将 filestobehere 子目录移动到自身,这可以预见地失败了(但是我确实看到了不同的错误)。

仅使用一个文件姓名使用 -Exclude 修复了您在 PowerShell (Core) 7+ 中的命令的问题,这是一个错误Windows PowerShell防止将排除的名称作为(可能位置隐含的)-Destination 参数。

适用于两个 PowerShell 版本的解决方案:

$dest = 'filestobehere' # OMIT the "."
Get-Item .* -Exclude $dest | Move-Item -Force -Destination $dest

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 2010-12-10
    相关资源
    最近更新 更多