我正在尝试将文件复制到新位置,维护目录结构.
$source = "c:\some\path\to\a\file.txt"
destination = "c:\a\more\different\path\to\the\file.txt"
Copy-Item $source $destination -Force -Recurse
Run Code Online (Sandbox Code Playgroud)
但我得到一个DirectoryNotFoundException:
Copy-Item : Could not find a part of the path 'c:\a\more\different\path\to\the\file.txt'
Run Code Online (Sandbox Code Playgroud) 使用Remove-Item命令时,即使使用-r和-Force参数,有时也会返回以下错误消息:
Remove-Item:无法删除项目C:\ Test Folder \ Test Folder \ Target:目录不为空。
特别是在Windows资源管理器中打开要删除的目录时,会发生这种情况。
现在,虽然可以通过关闭Windows资源管理器或不浏览该位置来避免这种情况,但是我在多用户环境中工作脚本(在这种环境下,人们有时会忘记关闭Windows资源管理器窗口,但我对删除的解决方案感兴趣)即使在Windows资源管理器中打开了整个文件夹和目录。
有没有比-Force我可以设置的功能更强大的选项了?
为了可靠地重现此内容,请创建文件夹C:\Test Folder\Origin并在其中填充一些文件和子文件夹(重要),然后采用以下脚本或类似的脚本并执行一次。现在打开C:\Test Folder\Target(在我的情况下,我使用C:\Test Folder\Target\Another Subfoldercontains A third file.txt)的子文件夹之一,然后尝试再次运行该脚本。您现在将得到错误。如果您第三次运行该脚本,则不会再次收到该错误(但是,根据我尚未确定的情况,该错误有时会第二次发生,然后再也不会发生,有时又每第二次发生一次)。
$SourcePath = "C:\Test Folder\Origin"
$TargetPath = "C:\Test Folder\Target"
if (Test-Path $TargetPath) {
Remove-Item -r $TargetPath -Force
}
New-Item -ItemType directory -Path $TargetPath
Copy-Item $SourcePath -Destination $TargetPath -Force -Recurse -Container
Run Code Online (Sandbox Code Playgroud)