处理脚本以获取Windows组件的状态。遇到一个挑战,循环遍历的结果,因为我想写出启用和禁用的组件。
我遇到的问题是,我无法从PSOBJECT中获得特定的值,而只能得到所有的东西。
#Microsoft Defender Statuses
$DefenderStatus = Get-MpComputerStatus | select-object AMServiceEnabled, AntispywareEnabled, AntivirusEnabled, BehaviorMonitorEnabled, IoavProtectionEnabled, IsTamperProtected, IsVirtualMachine, NISEnabled, OnAccessProtectionEnabled, RealTimeProtectionEnabled
#Write results to a PSOBJECT
$result = ([ordered]@{
'Anti-Virus'=$DefenderStatus.AntivirusEnabled
'Anti-Malware'=$DefenderStatus.AMServiceEnabled
'Anti-Spyware'=$DefenderStatus.AntispywareEnabled
'Behavior Monitor'=$DefenderStatus.BehaviorMonitorEnabled
'Office-Anti-Virus'=$DefenderStatus.IoavProtectionEnabled
'NIS'=$DefenderStatus.NISEnabled
'Access Protection'=$DefenderStatus.OnAccessProtectionEnabled
'R-T Protection'=$DefenderStatus.RealTimeProtectionEnabled
})
foreach ($Status in $result)
{
If ($Status.Values -eq $false)
{
Write-Host "$Status.Keys is Disabled"
$Disabled = $Disabled + ", " + $Status
}
Else
{
Write-Host "$Status.Keys is Enabled"
$Enabled = $Enabled + ", " + $Status
}
}发布于 2022-02-10 15:52:53
作为Theo comments,您要将结果存储在中,如果要迭代键值对,可以使用.GetEnumerator()或.Keys属性或.get_Keys()方法,例如:
$result = [ordered]@{
'Anti-Virus' = $true
'Anti-Malware' = $true
'Anti-Spyware' = $false
'Behavior Monitor' = $false
'Office-Anti-Virus' = $true
'NIS' = $false
'Access Protection' = $true
'R-T Protection' = $true
}
foreach($pair in $result.GetEnumerator()) {
# If the Value is $true
if($pair.Value) {
"{0} is Enabled" -f $pair.Key
continue
}
# If we're here last condition was $false
"{0} is Disabled" -f $pair.Key
}但是,由于$DefenderStatus似乎是一个对象,您还可以执行以下操作(如果是对象的 of object ),则需要更改:
$DefenderStatus = [PsCustomobject]@{
'Anti-Virus' = $true
'Anti-Malware' = $true
'Anti-Spyware' = $false
'Behavior Monitor' = $false
'Office-Anti-Virus' = $true
'NIS' = $false
'Access Protection' = $true
'R-T Protection' = $true
}
foreach($object in $DefenderStatus.PSObject.Properties) {
# Property Value
if($object.Value) {
"{0} is Enabled" -f $object.Name # Property Name
continue
}
"{0} is Disabled" -f $object.Name
}https://stackoverflow.com/questions/71067828
复制相似问题