我正在尝试将文件复制到新位置,维护目录结构.
$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)
ajk*_*ajk 97
-recurse
如果源是目录,则该选项仅创建目标文件夹结构.当源是文件时,Copy-Item要求目标是已存在的文件或目录.您可以通过以下几种方式解决这个问题.
选项1:复制目录而不是文件
$source = "c:\some\path\to\a\dir"; $destination = "c:\a\different\dir"
# No -force is required here, -recurse alone will do
Copy-Item $source $destination -Recurse
Run Code Online (Sandbox Code Playgroud)
选项2:首先 "触摸"文件然后覆盖它
$source = "c:\some\path\to\a\file.txt"; $destination = "c:\a\different\file.txt"
# Create the folder structure and empty destination file, similar to
# the Unix 'touch' command
New-Item -ItemType File -Path $destination -Force
Copy-Item $source $destination -Force
Run Code Online (Sandbox Code Playgroud)
这是一个oneliner来做到这一点。Split-Path
检索父文件夹,New-Item
创建它,然后Copy-Item
复制文件。请注意,目标文件将与源文件具有相同的文件名。此外,如果您需要将多个文件复制到与第二个文件相同的文件夹中,这将不起作用,您将收到An item with the specified name <destination direcory name> already exists
错误消息。
Copy-Item $source -Destination (New-Item -Path (Split-Path -Path $destination) -Type Directory)
Run Code Online (Sandbox Code Playgroud)
或者,使用PS3.0以后,您只需使用New-Item直接创建目标文件夹,而无需创建"虚拟"文件,例如......
New-Item -Type dir \\target\1\2\3\4\5
Run Code Online (Sandbox Code Playgroud)
...将很高兴地创建\\ target\1\2\3\4\5结构,而不管它已经存在多少.