我正在尝试将一个文件复制到一个新的位置,同时保持目录结构。
$source = "c:\some\path\to\a\file.txt"
destination = "c:\a\more\different\path\to\the\file.txt"
Copy-Item $source $destination -Force -Recurse但是我得到了一个DirectoryNotFoundException
Copy-Item : Could not find a part of the path 'c:\a\more\different\path\to\the\file.txt'发布于 2011-09-23 10:23:34
如果源是目录,则-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选项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发布于 2015-08-28 11:00:05
或者,从PS3.0开始,您可以简单地使用New-Item来直接创建目标文件夹,而不必创建一个“虚拟”文件,例如...
New-Item -Type dir \\target\1\2\3\4\5...will愉快地创建了\target\1\2\3\4\5结构,而不管它已经存在多少。
发布于 2019-11-27 04:29:50
这里有一个单行代码来做这件事。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)https://stackoverflow.com/questions/7523497
复制相似问题