是否有Powershell"字符串不包含" cmdlet或者语法?
时间:2020-03-05 18:56:39 来源:igfitidea点击:
在Powershell中,我正在读取一个文本文件。然后,我在文本文件上执行一个Foreach-Object,仅对不包含$ arrayOfStringsNotInterestedIn中的字符串的行感兴趣
有人知道这个语法吗?
Get-Content $filename | Foreach-Object {$_}
解决方案
回答
我们可以使用-notmatch运算符获取不包含我们感兴趣的字符的行。
Get-Content $FileName | foreach-object { if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }
回答
如果$ arrayofStringsNotInterestedIn是[array],则应使用-notcontains:
Get-Content $FileName | foreach-object { ` if ($arrayofStringsNotInterestedIn -notcontains $_) { $) }
或者更好(IMO)
Get-Content $FileName | where { $arrayofStringsNotInterestedIn -notcontains $_}
回答
要排除包含$ arrayOfStringsNotInterestedIn中的任何字符串的行,应使用:
(Get-Content $FileName) -notmatch [String]::Join('|',$arrayofStringsNotInterestedIn)
Chris提出的代码仅在$ arrayofStringsNotInterestedIn包含要排除的完整行时才有效。