首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环通过PSOBJECT将值与字符串进行比较

循环通过PSOBJECT将值与字符串进行比较
EN

Stack Overflow用户
提问于 2022-02-10 15:28:53
回答 1查看 39关注 0票数 2

处理脚本以获取Windows组件的状态。遇到一个挑战,循环遍历的结果,因为我想写出启用和禁用的组件。

我遇到的问题是,我无法从PSOBJECT中获得特定的值,而只能得到所有的东西。

代码语言:javascript
复制
#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

   }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-10 15:52:53

作为Theo comments,您要将结果存储在中,如果要迭代键值对,可以使用.GetEnumerator().Keys属性或.get_Keys()方法,例如:

代码语言:javascript
复制
$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 ),则需要更改

代码语言:javascript
复制
$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
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71067828

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档