问题
The objective is to copy folders and files from a path to another path using PowerShell. However, I want to exclude certain files and folders from getting copied. I was able to exclude multiple files by adding them to the exclude list
Get-ChildItem -Path $source -Recurse -Exclude "web.config","body.css","Thumbs.db"
For excluding folders I added
$directory = @("Bin")
?{$_.fullname -notmatch $directory}
and the final copy script looks like
Get-ChildItem -Path $source -Recurse -Exclude "Web.config","body.css","Thumbs.db" | ?{$_.fullname -notmatch $directory} | 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)}}
This seems to work with a single folder, but when I add multiple folders to the excluded directories it does not seem to work.What can be done to exclude multiple folders?
回答1:
$source = 'source path'
$dest = 'destination path'
[string[]]$Excludes = @('file1','file2','folder1','folder2')
$files = Get-ChildItem -Path $source -Exclude $Excludes | %{
$allowed = $true
foreach ($exclude in $Excludes) {
if ((Split-Path $_.FullName -Parent) -match $exclude) {
$allowed = $false
break
}
}
if ($allowed) {
$_.FullName
}
}
copy-item $source $dest -force -recurse
The above code excludes multiple folders listed in $Excludes array and copy the remaining contents to the destination folder
回答2:
Try this:
$excluded = @("Web.config", "body.css","Thumbs.db")
Get-ChildItem -Path $source -Recurse -Exclude $excluded
From the comment, in case you want to exclude folders, you can use something like this:
Get-ChildItem -Path $source -Directory -Recurse |
? { $_.FullName -inotmatch 'foldername' }
OR you can check the container first then do this:
Get-ChildItem -Path $source -Recurse |
? { $_.PsIsContainer -and $_.FullName -notmatch 'foldername' }
回答3:
Because $directory
is an array, you should be looking to match its contents and not itself (it is annoying that powershell lets single-element arrays be treated like their contents).
You can try:
?{$directory -contains $_.fullname}
Instead of:
?{$_.fullname -notmatch $directory}
来源:https://stackoverflow.com/questions/45318170/excluding-multiple-folders-when-copying-using-powershell