PowerShell Copy-Item 不创建子文件夹

时间:2021-03-27 14:18:19

标签: 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'.

2 个答案:

答案 0 :(得分:1)

Copy-item 没有创建文件夹的功能,需要事先创建

 Copy-Item $fullsrc $(new-item -ItemType Directory -Path $fulldst) -Recurse -Force -Verbose -ErrorAction SilentlyContinue

答案 1 :(得分:1)

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

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

Copy-Item $fullsrc $fulldst -Force -Verbose

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