Home > database >  Skip file copy if target exist - PowerShell
Skip file copy if target exist - PowerShell

Time:10-26

Can you please help? I have the below PowerShell code to copy a file (test.txt) into each user's roaming folder. It works. but I want to skip copying the file if test-old.txt (this is previously re-named file) exists already. Thank you for your help in advance.

fyi - I am happy to have a new code altogether if that works.

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

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

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

CodePudding user response:

Assuming the path for test-old.txt would be each user's ..\SAP\Common\ folder you would only need to add an if condition to your existing code to check if the file exists on said folder. A simple way to do this is with Test-Path.

Remember to add -Force switch to Get-ChildItem if you want to target Default and Default User folders.

$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
    }
}
  • Related