Copy-Item应该创建目标目录结构吗?

Ev.*_*Ev. 47 powershell

我正在尝试将文件复制到新位置,维护目录结构.

$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)

  • 谢谢谢伊.触摸方法非常方便,无需递归遍历文件夹. (4认同)
  • 有趣的是,“触摸”创建目录和文件,并且该文件是一个单行文件..如果您在记事本中打开文件(无论扩展名是什么)...该文件都具有〜原始名称的全名。 ..作为(text?)文件的line1。然后,复制项目非常高兴所有文件夹都正确存在。谢谢!我已经将您的答案扩展为这里的问题的答案:http://stackoverflow.com/questions/42818014/powershell-copy-files-with-a-blacklist-exclude-and-a-whitelist-include/42819089# 42819089 (2认同)

Lop*_*pez 9

这是一个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)

  • 现有目录的问题可以通过将“-Force”传递给 New-Item cmdlet 来解决。 (5认同)

Mik*_*ike 8

或者,使用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结构,而不管它已经存在多少.