如果目标存在,跳过文件复制- PowerShell



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

供参考-我很高兴有一个新的代码,如果工作的话。

$Source = '\ser04hAppsDatatest.txt'
$Destination = 'C:users*AppDataRoamingSAPCommon'
Get-ChildItem $Destination | ForEach-Object {Copy-Item -Path $Source -Destination $_ -Force}

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

如果您想要针对DefaultDefault User文件夹,请记住将-Force开关添加到Get-ChildItem

$Source = '\ser04hAppsDatatest.xml'
$Destination = 'C:users*AppDataRoamingSAPCommon'
Get-ChildItem $Destination | ForEach-Object {

$testOld = Join-Path $_.FullName -ChildPath 'test-old.txt'
if(-not(Test-Path $testOld))
{
Copy-Item -Path $Source -Destination $_ -Force
}
}

最新更新