Wojciech Szabowicz
Wojciech Szabowicz

Reputation: 4198

Copy-Item with exclude files and folders in powershell

I have a question. I want to copy content of one directory into another and made some progress. But, at the moment I'm stuck because if I can define array of files to exclude I have a problem with array of folders. So the arrays looks like:

$excludeFiles = @('app.config', 'file.exe')
$excludeFolders = @('Logs', 'Reports', 'Backup', 'Output')

It works when there is only one item in $excludeFolders array, but if I add multiple items, it copies all folders without excluding them.

Script I have:

Get-ChildItem -Path $binSolutionFolder -Recurse -Exclude $excludeFiles | 
where { $excludeFolders -eq $null -or $_.FullName.Replace($binSolutionFolder, "") -notmatch $excludeFolders } |
Copy-Item -Destination {
    if ($_.PSIsContainer) {
        Join-Path $deployFolderDir $_.Parent.FullName.Substring($binSolutionFolder.length -1)
    }
    else {
        Join-Path $deployFolderDir $_.FullName.Substring($binSolutionFolder.length -1)
    }
} -Force -Exclude $excludeFiles

Where $binSolutionFolder is source and $deployFolderDir is target. Files work fine, but with folders I've run out of ideas.

Upvotes: 0

Views: 6283

Answers (1)

Frode F.
Frode F.

Reputation: 54881

-notmatch uses a regex-pattern and not a collection. To match against a collection of words you could use -notin $excludedfolders, but if the path includes 2+ level of folders or just a simple \ then the test would fail.

I would use -notmatch, but first create a regex-pattern that checks all folders at ones. Ex:

$excludeFiles = @('app.config', 'file.exe') 
$excludeFolders = @('Logs', 'Reports', 'Backup', 'Output','Desktop')
$excludeFoldersRegex = $excludeFolders -join '|'

Get-ChildItem -Path $binSolutionFolder -Recurse -Exclude $excludeFiles | 
where { $_.FullName.Replace($binSolutionFolder, "") -notmatch $excludeFoldersRegex } |
.....

Upvotes: 2

Related Questions