You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell命令链执行输出异常,需同时获取OS版本与AV状态

问题分析与解决

出现重复值和null的核心原因是Invoke-Command脚本块返回了多个独立对象(原Windows Defender状态对象+Get-ComputerInfo返回的对象),PowerShell会自动将这些对象合并为数组,导致最终输出的每个字段被展开为包含多个值的集合(部分对象没有对应属性就显示null)。

修复方法:在脚本块内整合所有信息到单个自定义对象

将Windows Defender状态和操作系统版本信息合并到同一个输出对象中,确保Invoke-Command只返回单一结构的对象,避免数组化问题。

修改后的Get-AntiMalwareStatus函数示例:

function Get-AntiMalwareStatus {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string[]]$ComputerName
    )

    Invoke-Command -ComputerName $ComputerName -ScriptBlock {
        # 获取Windows Defender状态
        $avStatus = Get-MpComputerStatus
        
        # 直接提取操作系统名称的字符串值
        $osName = (Get-ComputerInfo).WindowsProductName

        # 整合为单个自定义对象输出
        [PSCustomObject]@{
            ComputerName        = $env:COMPUTERNAME
            OSVersion           = $osName
            AMServiceEnabled    = $avStatus.AMServiceEnabled
            AntivirusEnabled    = $avStatus.AntivirusEnabled
            AntispywareEnabled  = $avStatus.AntispywareEnabled
            RealTimeProtectionEnabled = $avStatus.RealTimeProtectionEnabled
            LastQuickScanTime   = $avStatus.LastQuickScanTime
            LastFullScanTime    = $avStatus.LastFullScanTime
        }
    } | Select-Object -Property ComputerName, OSVersion, AMServiceEnabled, AntivirusEnabled, AntispywareEnabled, RealTimeProtectionEnabled, LastQuickScanTime, LastFullScanTime
}

关键细节说明

  1. 直接提取属性值:用(Get-ComputerInfo).WindowsProductName而非Get-ComputerInfo | select WindowsProductName,后者会返回带属性的对象,前者直接返回字符串值,避免嵌套对象导致的属性展开问题。
  2. 单一输出对象:通过[PSCustomObject]将所有字段打包成一个对象,确保Invoke-Command每次只返回一个对象,PowerShell不会自动将结果转为数组。
  3. 本地筛选属性:在Invoke-Command之后用Select-Object统一筛选字段,避免远程返回的对象携带多余属性。

验证效果

调用函数时,输出的每个字段都会是单一有效值,不会再出现数组或null:

Get-AntiMalwareStatus -ComputerName "Server01", "Server02"

内容的提问来源于stack exchange,提问作者tpcolson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:22:39