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

17,239

Solution 1

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

Solution 2

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

$sourceFileList = Get-ChildItem "C:\inetpub\wwwroot\DemoSite" -Recurse

foreach ($item in $sourceFileList)
{
    $destinationPath = $item.Path.Replace($Source,$Destination)
    #For every *.csproj and *.config files, check whether the file exists in destination
    if ($item.extension -eq ".csproj" -or $item.extension -eq ".config")
    {
        if ((Test-Path $destinationPath) -ne $true)
        {
            Copy-Item $item -Destination $destinationPath -Force
        }
    }
    #If not *.csproj or *.config file then copy it directly
    else
    {
        Copy-Item $item -Destination $destinationPath -Force
    }
}
Share:
17,239
Nirman
Author by

Nirman

Updated on June 13, 2022

Comments

  • Nirman
    Nirman almost 2 years

    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

  • Zev
    Zev over 5 years
    Welcome! Please include an explanation with your answer. Code only answers get sent to the "Low Quality Posts" review queue for potential deletion. You can always edit and improve on your answer.