Working on a script to get the status of Windows Defender components. Running into a challenge looping through the results from Get-MpComputerStatus as I'm wanting to write out which components are enabled and disabled.
The issue that I'm running into is I'm not able to get the specific value from the PSOBJECT and only get everything.
#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
}
}
CodePudding user response:
As Theo comments, you're storing the results in an ordered hash table, if you want to iterate over the Key-Value pairs you could use .GetEnumerator()
or .Keys
property or .get_Keys()
method, for example:
$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
}
However, since $DefenderStatus
seem to be an object you could also do the following (if it was an object[]
(array of objects) this would need to be changed):
$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
}