首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在PowerShell中有任何方法来压缩多个Where对象条件吗?

在PowerShell中有任何方法来压缩多个Where对象条件吗?
EN

Stack Overflow用户
提问于 2022-05-11 13:17:07
回答 1查看 77关注 0票数 1

初学者在这里,我有一个脚本,连接到多个文件服务器,并递归通过目录,寻找超过90天的文件。一切都很好。

我使用get -include和-exclude来过滤我想要报告的文件,但是我也需要过滤某些目录,而且get项目不能过滤目录,所以我将结果传递到Where,然后将$_.FullName属性与我想要排除的字符串进行比较。

我的问题是,我必须定期调整我要过滤的目录名,这取决于客户端将其文件命名为什么,并且管理脚本有点失控,因为我必须继续向get-childitem项目行添加-and ($_.FullName -notMatch "BACKUPS")条件。

以下是我的相关代码:

代码语言:javascript
运行
复制
$Exclusions = ('*M.vbk','*W.vbk','*Y.vbk')
$Files = Get-ChildItem $TargetFolder -include ('*.vib','*.vbk','*.vbm','*.vrb') -Exclude $Exclusions -Recurse -File | 
         Where {($_.LastWriteTime -le $LastWrite) -and 
             ($_.FullName -notMatch "BACKUPS") -and 
             ($_.FullName -notMatch "Justin") -and 
             ($_.FullName -notMatch "Monthly") -and 
             ($_.FullName -notMatch "Template") -and 
             ($_.FullName -notMatch "JIMMY") -and 
             ($_.FullName -notMatch "ISAAC")}

我将$Exclusions变量设置为在Get中使用,这样我就可以根据需要调整一个变量。是否有一种方法可以将所有个人($.FullName -notMatch "JIMMY")条目压缩为只使用一个变量(如.($.FullName -notMatch $DirectoryListVariable)?

基本上,如果可能的话,我只需要让它更容易管理和改变。如果没有,我可以继续添加新的行,但我希望有一个更好的方法。

耽误您时间,实在对不起!

EN

回答 1

Stack Overflow用户

发布于 2022-05-11 13:34:49

使用regex alternation (|)匹配多种模式中的任何一种:

代码语言:javascript
运行
复制
# Array of name substrings to exclude.
$namesToExclude = 'BACKUPS', 'Monthly', 'Justin', 'Template', 'JIMMY', 'ISAAC' # , ...

# ...
... | Where-Object { 
  $_.LastWriteTime -le $LastWrite -and 
  $_.FullName -notmatch ($namesToExclude -join '|')
}
  • 对于区分大小写的匹配,请使用-cnotmatch
  • 作为一种替代方法,可以定义一个模式数组,然后使用-join|来形成单个字符串('BACKUPS|Monthly|...'),您可以选择首先定义您的名称作为这样一个字符串的一部分。
代码语言:javascript
运行
复制
- Do note that the resulting string must be a valid regex; that is, the individual names are interpreted as regexes (subexpressions) too.
代码语言:javascript
运行
复制
- If that is undesired (note that it isn't a problem here, because the specific sample names are also treated literally as regexes), you can escape them with `[regex]::Escape()`.
  • 最后,请注意,-match及其变体执行子字符串(子表达式)匹配;要完全匹配输入字符串,需要锚定表达式,即使用^ (字符串的开始)和$ (字符串的结尾)。 'food' -match 'oo'$true,但'food' -match '^oo$'不是('oo' -match '^oo$'是)。
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72201774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档