错误:无法索引到Powershell中的类型对象

Iro*_*nic 5 powershell

下面是powershell脚本.

$Requests = Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$($SiteCode) -ComputerName $SiteServer  |  Select-Object User,Application,CurrentState,Comments | Sort-Object User
    $Count = @($Requests).Count
        for ($i=0; $i -lt $count; $i++) {
            if ($Requests[$i].CurrentState -eq '1') {
                $Requests[$i].CurrentState = "Pending"
                $checkbox1.Enabled = $true
            }
Run Code Online (Sandbox Code Playgroud)

当我执行脚本时,我收到以下错误.

 Unable to index into an object of type System.Management.Automation.PSObject.
if ($Requests[ <<<< $i].CurrentState -eq '1') {
    + CategoryInfo          : InvalidOperation: (0:Int32) [], RuntimeException
    + FullyQualifiedErrorId : CannotIndex
Run Code Online (Sandbox Code Playgroud)

我想做的是我将值(1)替换为待定.

Mat*_*sen 7

如果Get-WmiObject仅返回单个实例,$Requests则将是单个对象,而不是集合.将Get-WmiObject调用包含在数组子表达式operator(@())中,使其返回单项数组:

$Requests = @(Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$($SiteCode) -ComputerName $SiteServer  |  Select-Object User,Application,CurrentState,Comments | Sort-Object User)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢`[Array] $ Request = Get-WMIObject ...`更好. (3认同)