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

18.2k views Asked by At

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

4

There are 4 answers

0
Micky Balladelli On BEST ANSWER

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
0
RinoTom On
$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
    }
}
0
Upo001 On

SKaDT's solution worked for me.

Copy-Item -Path (Get-ChildItem -Path E:\source\*.iso).FullName -Destination E:\destination -Exclude (Get-ChildItem -Path E:\destination\*.iso).Name -Verbose

(Get-ChildItem -Path E:\source\*.iso).FullName will collect all source files with full drive, path and filenames. With -Exclude parameter, (Get-ChildItem -Path E:\destination\*.iso).Name collects all *.iso files in the destination folder and excludes all of them. Result: copy all *.iso files from source to destination but excludes all *.iso files that exist in the destination folder.

1
SKaDT On

you can use that oneline command to copy only files that did't exist at destination location, for Task Scheduler for example

Copy-Item -Path (Get-ChildItem -Path E:\source\*.iso).FullName -Destination E:\destination -Exclude (Get-ChildItem -Path E:\destination\*.iso).Name -Verbose

cmdlet get all files on folder by mask (*.iso), after that seek the destination folder and exclude all filenames that exist at destination folder