如果我有一个包含计算机名称的数组,例如:
foows001
foows002
barws003
barws004
zzzws001
zzzws002
...然后我用foreach
循环处理这个数组:
foreach ($item in $Computers) {
if ( $item.hostname -like $ComputersToSearch ) {
Write-Host $item.hostname
}
我想为-like
使用多个值,并将它们存储在数组中以便于处理。
$ComputersToSearch = =@("foo*","bar*")
我还尝试过第二次foreach
声明,但没有成功。关于如何处理这个的任何建议?
答案 0 :(得分:2)
您可以使用正则表达式来匹配多个表达式。
-join
上的|
)代码:
# Declare array of computer names
$ComputerList = @(
'foows001'
, 'foows002'
, 'barws003'
, 'barws004'
, 'zzzws001'
, 'zzzws002'
);
# Declare array of regular expression matches
$SearchList = @('^foo', '^bar') -join '|';
# Iterate of list of computers, and match against regular expression
foreach ($Computer in $ComputerList) {
if ($Computer -match $SearchList) {
Write-Host -Object "$Computer matched search criteria";
}
}
foows001 matched search criteria
foows002 matched search criteria
barws003 matched search criteria
barws004 matched search criteria