Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: Unable to index into an object of type in Powershell

Tags:

powershell

Below is powershell script.

$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 am getting 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 I am replacing value (1) to Pending.

like image 243
Roxx Avatar asked Jul 09 '15 08:07

Roxx


1 Answers

If Get-WmiObject returns just a single instance, $Requests will be a single object, not a collection. Enclose the Get-WmiObject call in the array subexpression operator (@()) to have it return a single-item array instead:

$Requests = @(Get-WmiObject -Class SMS_UserApplicationRequest -Namespace root/SMS/site_$($SiteCode) -ComputerName $SiteServer  |  Select-Object User,Application,CurrentState,Comments | Sort-Object User)
like image 84
Mathias R. Jessen Avatar answered Sep 26 '22 11:09

Mathias R. Jessen