Powershell Copy-Item - Exclude only if the file exists in destination

Nirman picture Nirman · Nov 18, 2014 · Viewed 16.6k times · Source

Following is the exact scenario in my powershell script.

$Source = "C:\MyTestWebsite\"
$Destination = "C:\inetpub\wwwroot\DemoSite"
$ExcludeItems = @(".config", ".csproj")

Copy-Item "$Source\*" -Destination "$Destination" -Exclude $ExcludeItems -Recurse -Force

I want this code to copy .config and .csproj files if they are not existing in destination folder. The current script simply excludes them irrespective to whether they exist or not. The objective is,I do not want the script to overwrite .config and .csproj files, but it should copy them if they are not existing at destination.

Any idea of what corrections are required in the scripts?

Any help on this will be much appreciated.

Thanks

Answer

Micky Balladelli picture Micky Balladelli · Nov 18, 2014

This should be pretty close to what you want to do

$Source = "C:\MyTestWebsite\"
$Destination = "C:\inetpub\wwwroot\DemoSite"

$ExcludeItems = @()
if (Test-Path "$Destination\*.config")
{
    $ExcludeItems += "*.config"
}
if (Test-Path "$Destination\*.csproj")
{
    $ExcludeItems += "*.csproj"
}

Copy-Item "$Source\*" -Destination "$Destination" -Exclude $ExcludeItems -Recurse -Force