从文件中排除如果行包含从变量A OR B值

问题描述 投票:0回答:1

我使用的StreamWriter写入一个文件,我想排除匹配包含两个参数的值,任何行。我曾尝试下面的代码,但是当我包括第二条件($file_stream -notmatch $exclude_permission_type)它不输出任何值。

$exclude_user_accounts = 'account1', 'account2', 'account3' 
$exclude_permission_type = 'WRITE'

while ($file_stream = $report_input.ReadLine()) {
  if ($file_stream -notmatch $exclude_user_accounts -and $file_stream -notmatch $exclude_permission_type) { 
    $_report_output.WriteLine($file_stream)
  } 
}
powershell
1个回答
0
投票

这显然是不可能的,你的代码已经工作过你想要的方式,即使只有第一个条件,因为字符串不能匹配字符串数组。 <string> -notmatch <array>将始终评估为true即使该数组包含完全匹配。你不能这样做部分匹配一样,在所有。

建立从你所有的过滤字符串一个正则表达式:

$excludes = 'account1', 'account2', 'account3', 'WRITE'

$re = ($excludes | ForEach-Object {[regex]::Escape($_)}) -join '|'

然后筛选使用正则表达式你的字符串:

if ($file_stream -notmatch $re) {
    $_report_output.WriteLine($file_stream)
} 
© www.soinside.com 2019 - 2024. All rights reserved.