我正试图在Where对象的当前筛选器中构建一个排除列表。
目前我有以下几种:
Where-Object {($_.Enabled -EQ $true) -AND ($_.LastRunOutcome -eq 'failed')}
我想添加一个额外的过滤器,添加一个双过滤器。所以我的主要过滤器是Enabled和LastRunOutcome,它将应用于所有返回的对象。
但我也想添加一个过滤器,说明如果Name和SqlInstance匹配,则字符串不包括在输出中。
Where-Object {($_.Enabled -EQ $true -AND $_.LastRunOutcome -EQ 'failed' -AND $_.Name -NE "Import - Ad Hoc" -AND $_.SqlInstance -EQ "ServerName")}
如果您能帮助我计算多个Name/SqlInstance值,则可获得额外积分。例如ServerA和NameA排除、ServerB和NameB排除等。这将允许将来的排除值。
这就是您在简单案例中想要的吗?
用于演示/测试的输入阵列:
$sqlInfo = @(
@{ Enabled = $true; LastRunOutcome = 'failed'; Name = 'name0'; SqlInstance = 'instance0' }
@{ Enabled = $false; LastRunOutcome = 'failed'; Name = 'name0'; SqlInstance = 'instance0' }
@{ Enabled = $true; LastRunOutcome = 'succeeded'; Name = 'name0'; SqlInstance = 'instance0' }
@{ Enabled = $false; LastRunOutcome = 'succeeded'; Name = 'name0'; SqlInstance = 'instance0' }
@{ Enabled = $true; LastRunOutcome = 'failed'; Name = 'name0'; SqlInstance = 'instance1' }
@{ Enabled = $true; LastRunOutcome = 'failed'; Name = 'name1'; SqlInstance = 'instance0' }
@{ Enabled = $true; LastRunOutcome = 'failed'; Name = 'name1'; SqlInstance = 'instance1' }
)
过滤脚本:
$result = $sqlInfo | Where-Object { ($_.Enabled -eq $true -and $_.LastRunOutcome -eq 'failed') `
-and -not ($_.Name -eq 'name0' -and $_.SqlInstance -eq 'instance0')}
输出脚本和结果:
$result | ForEach-Object { [PSCustomObject]$_ } | Format-Table
Name LastRunOutcome SqlInstance Enabled
---- -------------- ----------- -------
name0 failed instance1 True
name1 failed instance0 True
name1 failed instance1 True
BONUS如果可以对服务器名称和实例执行某种串联,那么通过对字符串数组使用contains
在排除列表上进行筛选应该是相当直接的。
$exclusionSet = @(
'name0 -- instance0'
'name1 -- instance1'
)
$result = $sqlInfo | Where-Object { ($_.Enabled -eq $true -and $_.LastRunOutcome -eq 'failed') `
-and -not ($exclusionSet.Contains("$($_.Name) -- $($_.SqlInstance)" ) ) }
$result | ForEach-Object { [PSCustomObject]$_ } | Format-Table