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

旧巷老猫 提交于 2021-01-27 05:38:52

问题


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.


回答1:


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)



回答2:


You could try dealing with each object as it exits the pipeline, instead of trying to put them all into some sort of array and then dealing with them. E.g. something like this:

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


来源:https://stackoverflow.com/questions/31312353/error-unable-to-index-into-an-object-of-type-in-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!