首页 > 解决方案 > 如果目标存在则跳过文件复制 - PowerShell

问题描述

你能帮忙吗?我有以下 PowerShell 代码将文件 (test.txt) 复制到每个用户的漫游文件夹中。有用。test-old.txt但如果(这是以前重命名的文件)已经存在,我想跳过复制文件。提前谢谢你的帮助。

仅供参考 - 如果可行,我很高兴完全有一个新代码。

$Source = '\\ser04\h\AppsData\test.txt'

$Destination = 'C:\users\*\AppData\Roaming\SAP\Common\'

Get-ChildItem $Destination | ForEach-Object {Copy-Item -Path $Source -Destination $_ -Force}

标签: powershellcopyskipscript

解决方案


假设路径test-old.txt是每个用户的..\SAP\Common\文件夹,您只需向if现有代码添加一个条件以检查该文件是否存在于所述文件夹中。一个简单的方法是使用Test-Path.

如果要定位和文件夹,请记住添加-Force开关。Get-ChildItemDefaultDefault User

$Source = '\\ser04\h\AppsData\test.xml'
$Destination = 'C:\users\*\AppData\Roaming\SAP\Common\'

Get-ChildItem $Destination | ForEach-Object {
    
    $testOld = Join-Path $_.FullName -ChildPath 'test-old.txt'

    if(-not(Test-Path $testOld))
    {
        Copy-Item -Path $Source -Destination $_ -Force
    }
}

推荐阅读