1

I am trying to sanitize my source code into another folder using Powershell:

dir $sourceDir\* -Recurse -Exclude */bin/*,*/obj/* -Include *.sln, *.myapp, *.vb, *.resx, *.settings, *.vbproj, *.ico, *.xml

And it seems like everything is working fine, however, -Include directive sort of whitelists the file before -Exclude, so .XML files under /bin/, for example, are included. I would like -Exclude to take precedence over -Include, so always exclude /bin/ and /obj/ folders in the above script.

It is possible in Powershell, without writing too much code?

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • Does the behavior change if you put your exclude items in quotes?, i.e. `-Exclude "*/bin/*", "*/obj/*"` – David Dec 12 '13 at 20:56
  • @David: Nope, it's the same. I refactored into using an array of values, where I included quotes (it does not work otherwise), but that did not help resolve the problem. – Victor Zakharov Dec 12 '13 at 20:57

2 Answers2

2

You can switch to late filtering to exclude the directories you don't want:

dir $sourceDir\* -Recurse  -Include *.sln, *.myapp, *.vb, *.resx, *.settings, *.vbproj, *.ico, *.xml |
 where {$_.fullname -notmatch '\\bin\\|\\obj\\'}

Using -like instead of -match:

dir $sourceDir\* -Recurse  -Include *.sln, *.myapp, *.vb, *.resx, *.settings, *.vbproj, *.ico, *.xml |
 where { ($_.fullname -notlike '*\bin\*') -and ($_.fullname -notlike '*\obj\*') }
mjolinor
  • 66,130
  • 7
  • 114
  • 135
0

Here is my take on it:

param(
  $sourceDir="x:\Source",
  $targetDir="x:\Target"
)

function like($str,$patterns){
  foreach($pattern in $patterns) { if($str -like $pattern) { return $true; } }
  return $false;
}

$exclude = @(
"*\bin\*",
"*\obj\*"
);

$include = @(
"*.sln",
"*.myapp",
"*.vb",
"*.resx",
"*.settings",
"*.vbproj",
"*.ico",
"*.xml"
);

dir $sourceDir\* -Recurse -Include $include | where {
  !(like $_.fullname $exclude)
}

May not be very Powershell-ish, but it works. I used like function from here.

Any shorter answers are welcome - please go ahead and suggest an alternative.

Community
  • 1
  • 1
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151