当目标文件夹存在或不存在时复制项目

问题描述 投票:0回答:2

当目标文件夹存在时,定义复制文件的正确方法此处

Copy-Item 'C:\Source\*' 'C:\Destination' -Recurse -Force

如果目标文件夹不存在,源子文件夹中的某些文件将直接复制到目标中,而不保留原始文件夹结构。

有没有办法使用单个

Copy-Item
命令来解决这两种情况并保留文件夹结构?还是对 Powershell 的要求太多了?

powershell copy copy-item
2个回答
2
投票

您可能想要使用带有测试路径的 if 语句

这是我用来解决这个问题的脚本

$ValidPath = Test-Path -Path c:\temp

If ($ValidPath -eq $False){

    New-Item -Path "c:\temp" -ItemType directory
    Copy-Item -Path "c:\temp" -Destination "c:\temp2" -force
}

Else {
      Copy-Item -Path "c:\temp" -Destination "c:\temp2" -force
     }

0
投票

Bonneau21 发布内容的修订版本:

$SourceFolder = "C:\my\source\dir\*" # Asterisk means the contents of dir are copied and not the dir itself
$TargetFolder = "C:\my\target\dir"

$DoesTargetFolderExist = Test-Path -Path $TargetFolder

If ($DoesTargetFolderExist -eq $False) {
    New-Item -Path $TargetFolder -ItemType directory
}

Copy-Item -Path $SourceFolder -Destination $TargetFolder -Recurse -Force
© www.soinside.com 2019 - 2024. All rights reserved.