Error: Cannot index an object of type Powershell

The following is a powershell script option.

$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
            }

when i execute the script i get the following error.

 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

What I want to do is replace the value (1) with Pending.

+4
source share
2 answers

If it Get-WmiObjectreturns only one instance, it $Requestswill be the only object, not a collection. Include a call Get-WmiObjectin the array subexpression operator ( @()) so that it instead returns an array with one element:

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

You can try to deal with each object when it exits the pipeline, instead of trying to put them all in some sort of array, and then deal with them. For instance. something like that:

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
            }
    }
+2
source

All Articles