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

时间:2015-07-09 08:40:41

标签: 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
            }

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

 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

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

2 个答案:

答案 0 :(得分:7)

如果Get-WmiObject只返回一个实例,$Requests将是一个对象,而不是一个集合。将Get-WmiObject调用包含在数组子表达式运算符(@())中,以使其返回单项数组:

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

答案 1 :(得分:2)

您可以尝试在退出管道时处理每个对象,而不是尝试将它们全部放入某种数组然后处理它们。例如。像这样的东西:

Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$($SiteCode) -ComputerName $SiteServer `
  | Select-Object User,Application,CurrentState,Comments `
  | Sort-Object User `
  | ForEach-Object {
        If ($_.CurrentState -eq '1') {
                $_.CurrentState = "Pending"
                $checkbox1.Enabled = $true
            }
    }