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

PowerShell函数返回PSCustomObject后无法访问属性的问题

问题分析与解决:PowerShell函数返回对象无法访问属性

核心问题

你的AppInstallStatus函数在创建PSCustomObject后,通过| Format-List将对象转换成了格式化输出专用的对象(类型为Microsoft.PowerShell.Commands.Internal.Format.FormatEntryData),而非保留原始的自定义对象。这种格式化对象仅用于控制台输出展示,不具备原对象的属性,因此赋值给变量后无法访问ApplicationName等属性。

解决方案

移除函数内部的| Format-List,直接返回原始的PSCustomObject。如果需要在控制台查看时格式化输出,在调用函数时添加| Format-List即可,不要在函数内部修改返回对象的类型。

修正后的完整代码

$appName = "Trend"
$appTargetVer = 14.0
$appSvc = "ntrtscan"

Function AppInstallStatus{
    param(
        $appName,
        $appTargetVer
    )
    
    $AppInstTest = Get-CimInstance Win32_Product | Where-Object {$_.Name -match $appName} | Select-Object -Property Name,Vendor,Version,Caption

    $InstallStatus = $false
    $VerStatus = $false
    $CurVer = $null

    if($AppInstTest.Name -match $appName){
        $InstallStatus = $true        
        if([version]$AppInstTest.Version -ge [version]$appTargetVer){
            $VerStatus = $true
            $CurVer = $AppInstTest.Version
        }
    }

    # 移除| Format-List,直接返回原始自定义对象
    [PSCustomObject]@{            
        AppNameTest=$appName
        AppTargetVerTest=$appTargetVer
        ApplicationName = $AppInstTest.Name
        ApplicationCurrentVer = $AppInstTest.Version
        AppInstallStatus = $InstallStatus
        ApplicationVersionStatus = $VerStatus
    }
}

Function AppService{
    param(
        $appSvc
    )
    
    $AppTest = Get-Service -Name $appSvc -ErrorAction SilentlyContinue
    # 直接返回布尔值,简化逻辑
    return $AppTest -and $AppTest.Status -eq "Running"
}

# 调用函数并获取原始对象
$InstallInfo = AppInstallStatus $appName $appTargetVer 
$SvcStatus = AppService $appSvc

# 现在可以正常访问属性
Write-host "应用名称: $($InstallInfo.ApplicationName)"
Write-host "安装状态: $($InstallInfo.AppInstallStatus)"
Write-host "版本达标状态: $($InstallInfo.ApplicationVersionStatus)"
Write-host "服务运行状态: $SvcStatus"

# 整合所有结果为一个对象,方便后续输出到文件
$FinalResult = [PSCustomObject]@{
    ComputerName = $env:COMPUTERNAME
    AppName = $InstallInfo.AppNameTest
    TargetVersion = $InstallInfo.AppTargetVerTest
    InstalledVersion = $InstallInfo.ApplicationCurrentVer
    IsInstalled = $InstallInfo.AppInstallStatus
    IsVersionCompliant = $InstallInfo.ApplicationVersionStatus
    ServiceRunning = $SvcStatus
}

# 输出到CSV文件
$FinalResult | Export-Csv -Path ".\AppHealthCheck_$($env:COMPUTERNAME).csv" -NoTypeInformation -Encoding UTF8

额外优化说明

  1. 版本比较时,将版本字符串转换为[version]类型,避免字符串比较导致的逻辑错误(比如"14.0"和"14.0.0"的字符串比较问题)
  2. AppService函数添加-ErrorAction SilentlyContinue避免服务不存在时抛出错误,同时简化返回逻辑
  3. 新增了整合结果并输出到CSV的逻辑,符合你后续批量检查、生成合规文件的需求
  4. 初始化变量默认值,避免未进入分支时变量未定义的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 05:55:04