Copy and delete folders in PowerShell excluding specific files

The following command first retrieves the content of a folder recursively with the Get-ChildItem cmdlet, and then through piping mechanism, if the contained item it’s not a sub-folder, it deletes it.

gci -Path “D:/yourFolder” -Recurse -Exclude “*.config”,”*.txt” | foreach ($_) {
    if (!$_.PSIsContainer) { Remove-Item $_.FullName -Verbose -Force }

For the exclusion list, you should normally be able to specify items using wildcards, specific file names and even folder names

$dest = “d:/yourDestinationFolder”
$source = “d:/yourSourceFolder”
Get-ChildItem -Path $source -Recurse -Exclude “*.config”,”*.txt” |
    Copy-Item -Force -Destination {
        if ($_.GetType() -eq [System.IO.FileInfo]) {
            Join-Path $dest $_.FullName.Substring($source.length)
        } else {
            Join-Path $dest $_.Parent.FullName.Substring($source.length)

Note 1: Credits go to StackOverflow, IT blogs and alike, sites that helped me with the code when searching for solutions.
Note 2: Be aware that when copy-pasting, the quotes and possibly other characters get messed up by WordPress, you’ll have to replace them.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: