优先级 - 在Get-ChildItem中排除-Include over -Include

时间:2013-12-12 20:39:40

标签: powershell

我正在尝试使用Powershell将我的源代码清理到另一个文件夹中:

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

似乎一切正常,但是-Include指令在-Exclude之前将文件列入白名单,因此.XML下的/bin/文件是包括在内。我希望-Exclude优先于-Include,因此请始终在上述脚本中排除/bin//obj/个文件夹。

在Powershell中可以不写太多代码吗?

2 个答案:

答案 0 :(得分:2)

您可以切换到延迟过滤以排除您不想要的目录:

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

使用-like而不是-match:

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

答案 1 :(得分:0)

以下是我的看法:

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)
}

可能不是Powershell-ish,但它确实有效。我使用了like function from here

欢迎任何简短的答案 - 请继续并提出替代方案。