【问题标题】:Excluding multiple items from Get-ChildItem using Powershell version 4使用 Powershell 版本 4 从 Get-ChildItem 中排除多个项目
【发布时间】:2021-09-28 00:11:42
【问题描述】:

我正在遍历目录树,但试图过滤掉一些东西。

这是我拼凑的代码;

Get-ChildItem -Path $pathName -recurse -Filter index.aspx* -Exclude */stocklist/* | ? {$_.fullname -NotMatch "\\\s*_"} | Where {$_.FullName -notlike "*\assets\*" -or $_.FullName -notlike ".bk"}
  • 从返回的项目中删除名称 index.aspx。
  • 我想过滤掉所有以下划线开头的文件。
  • 排除路径中包含 /stocklist/ 的任何内容。
  • 排除路径中包含 /assets/ 的任何内容。
  • 并排除路径中包含 .bk 的任何内容。

除了路径中的 .bk 之外,这对所有内容都有效。我很确定这是我的语法错误。

提前致谢。

【问题讨论】:

  • 我假设 .bk 是扩展名?使用“*.bk”。
  • 不,这不是扩展。它是路径名 EG c:/foo/something.bk/anotherthing/ 的一部分。谢谢。
  • 只要使用-notmatch '\.bk\b'
  • 只是在上一条Where{ } 语句上的注释,您想使用-and 而不是-or,因为-or 会传递任何比较结果之一返回$true 的地方。所以如果它有\assets` in the path, but not .bk`,第二个条件将解析为$true,它会通过过滤器,这不是你的意图。要像您一样使用它,您需要不使用负比较器,然后将整个东西放在括号中并像这样Where { ! ($_.FullName -like "*\assets\*" -or $_.FullName -like "*.bk*")} 对它执行-not(或!)

标签: powershell filtering powershell-4.0 get-childitem


【解决方案1】:

您可以在 Where-Object 子句中创建一个正则表达式字符串并在文件的 .DirectoryName 属性上使用 -notmatch 来排除您不需要的文件:

$excludes = '/stocklist/', '/assets/', '.bk'
# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($excludes | ForEach-Object { [Regex]::Escape($_) }) -join '|'

Get-ChildItem -Path $pathName -Filter 'index.aspx*' -File -Recurse |
Where-Object{ $_.DirectoryName -notmatch $notThese -and $_.Name -notmatch '^\s*_' }

【讨论】:

  • 他们还想排除以下划线开头的文件,因此将您的 Where-Object 脚本块更新为 { $_.DirectoryName -notmatch $notThese -and $_.Name -notmatch '^\s*_' }。
  • @TheMadTechnician Ow.. 完全错过了。谢谢你,我已经更新了我的答案。 (尽管 OP 建议的过滤器 'index.aspx*' 应该已经解决了这个问题。)
  • ...而 我 错过了那一点。你完全正确,-filter 'index.aspx*' 会完全解决这个问题。
  • @TheMadTechnician 是的,但该过滤器可能只是一个示例,可以轻松更改为 '*index.aspx*'.. 在这种情况下,您的添加可以捕捉到这一点,再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-17
  • 1970-01-01
  • 1970-01-01
  • 2013-11-19
  • 2013-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多