首页 > 解决方案 > PowerShell Copy-Item 未创建子文件夹

问题描述

我希望 Copy-Item 复制到目标文件并在途中创建任何子文件夹,但我似乎无法让它工作。

Copy-Item $fullsrc $fulldst -Recurse -Force -Verbose

$fullsrc并且$fulldst是带有文件名的完整路径,因为目标文件名与源文件名不同。有没有办法让 Copy-Item 创建子文件夹然后复制文件?

VERBOSE: Performing the operation "Copy File" on target "Item: D:\mypath\logs\001.123.log
Destination: D:\newpath\newlogs\123.234.log".
Copy-Item : Could not find a part of the path 'D:\newpath\newlogs\123.234.log'.

标签: powershellcopy-item

解决方案


您必须自己创建目标文件的父目录。

# Split-Path with single parameter outputs the parent directory
$null = New-Item (Split-Path $fulldst) -ItemType Directory

Copy-Item $fullsrc $fulldst -Force -Verbose

请注意,-Recurse当您指定完整的源文件和目标文件路径时,switch 没有用,因此我将其删除。


推荐阅读