【问题标题】:Prioritize -Exclude over -Include in Get-ChildItem在 Get-ChildItem 中将 -Exclude 优先于 -Include
【发布时间】:2013-12-13 10:23:19
【问题描述】:

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

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

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

在Powershell中也可以,不用写太多代码?

【问题讨论】:

  • 如果您将排除项放在引号中,行为会改变吗?,即-Exclude "*/bin/*", "*/obj/*"
  • @David:不,是一样的。我重构为使用一个值数组,其中包含引号(否则它不起作用),但这无助于解决问题。

标签: powershell


【解决方案1】:

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

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\*') }

【讨论】:

  • 有没有办法避免正则表达式,即继续使用文件系统掩码(*?)?
  • 您也可以使用 -like 代替 -match。这将使用通配符匹配而不是正则表达式。
  • 感谢您的更新。是的,我将类似模式的使用优化为或多或少易于管理的代码片段。看我的回答。为您的努力 +1。
  • 以这个问题的受欢迎程度,不太可能出现更多答案。我会接受你的。
【解决方案2】:

这是我的看法:

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,但它可以工作。我用like function from here

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2019-02-17
    • 2017-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多