Exclude few sub folders while copying to remote server

Ian Xue 81 Reputation points
2020-08-07T10:09:59.543+00:00

Hi.

I am trying to copy the folder and files from one server to another, based on a configuration xml.

The source folder contains data as below:

Backup

Backup\folder1

Backup\folder2

Backup\folder3 .. like this

I want to exclude folder2, folder4, folder5 and copy the other folders to destination.

Also, when copying other folders, I want to copy those folders and only the files ending with .bak in them.

My current code is copying all files and folders.

// config.xml

<Config>
<Test>
<SourceDBBackupPath>\\server\D$\BACKUP</SourceDBBackupPath>
<DestinationRestorePath>\\server1\e$\BACKUP\;\\server2\e$\BACKUP\</DestinationRestorePath>
<DestinationServer>server1;server2</DestinationServer>
</Test>
</Config>


function CopyBackup($Region)
{
    if($Region -ieq "Test" )
    {
       $XPath = "Config/Test"
       $Xvalues =   Select-Xml -Path $configFile -XPath $Xpath | Select-Object -ExpandProperty Node

       $DestinationServers = $Xvalues.DestinationServer -Split ";"
       $SourcePath = $Xvalues.SourceDBBackupPath
       $DestinationPaths = $Xvalues.DestinationRestorePath -Split ";"      

       foreach ($DestinationPath in $DestinationPaths){
           Copy-Item $SourcePath -Destination $DestinationPath  -Recurse -force
       }     
       Write-Host "Files copied" 

      }
    }

Thanks

source link
https://social.technet.microsoft.com/Forums/en-US/df09db52-1af8-4ef0-9999-57d8496a148a/exclude-few-sub-folders-while-copying-to-remote-server?forum=winserverpowershell

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,455 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 34,191 Reputation points Microsoft Vendor
    2020-08-07T10:12:39.597+00:00

    Hi,

    You could create a list of all the items and then filter out what is needed. I did some test on my local machine and the code is like this

    $ExclusionPath = @("folder2","folder4","folder5")
    Get-ChildItem $SourcePath -filter *.bak -recurse | 
    ForEach-Object {
        if($ExclusionPath -notcontains $_.Directory.Name){
            Copy-Item $_.FullName -Destination $DestinationPath
        }
    }
    

    Or you can just use robocopy. It's much easier.

    robocopy $SourcePath $DestinationPath *.txt /E /XD $ExclusionPath
    
    0 comments No comments