Powershell 2 copy-item如果不存在则创建一个文件夹

Mic*_*Mit 60 powershell copy powershell-2.0

$from = "\\something\1 XLS\2010_04_22\*"
$to =  "c:\out\1 XLS\2010_04_22\"
copy-item $from $to -Recurse 
Run Code Online (Sandbox Code Playgroud)

如果c:\ out\1 XLS\2010_04_22 \确实存在,则此方法有效.如果不存在,是否可以使用单个命令创建"c:\ out\1 XLS\2010_04_22 \".

Fri*_*ave 98

在PowerShell 2.0中,仍然无法使用Copy-Item cmdlet创建目标文件夹,您需要这样的代码:

$destinationFolder = "C:\My Stuff\Subdir"

if (!(Test-Path -path $destinationFolder)) {New-Item $destinationFolder -Type Directory}
Copy-Item "\\server1\Upgrade.exe" -Destination $destinationFolder
Run Code Online (Sandbox Code Playgroud)

如果在Copy-Item中使用-Recurse,它将在目标中创建源结构的所有子文件夹,但它不会创建实际的目标文件夹,即使使用-Force也是如此.

  • 当目标文件夹不存在时,我也遇到了错误的行为 (2认同)
  • 谢谢。这是我一直在寻找的答案。糟糕的是没有切换到创建目标文件夹。 (2认同)

Sha*_*evy 74

是的,添加-Force参数.

copy-item $from $to -Recurse -Force
Run Code Online (Sandbox Code Playgroud)

  • 这适用于整个目录,但如果我只是复制单个文件(所以我可以拥有状态)怎么办?当c:\ test2不存在时,如何将c:\ test1\file.txt复制到c:\ test2\file.txt?这就是我真正需要知道的事情.谢谢,加里 (71认同)
  • 我遇到了同样的问题并通过首先调用New-Item来解决它:`New-Item -Force $ to``Copy-Item -Force $ from $ to` (38认同)
  • 当人们知道它时,PowerShell很容易:) (3认同)

mju*_*udd 12

在PowerShell 3及更高版本中,我使用带有New-Item的Copy-Item.

copy-item -Path $file -Destination (new-item -type directory -force ("C:\Folder\sub\sub\" + $newSub)) -force -ea 0
Run Code Online (Sandbox Code Playgroud)

我没有在第2版中尝试过.