Home > other >  IndexOf Error in Dynamic Menu using PSRemotingJob
IndexOf Error in Dynamic Menu using PSRemotingJob

Time:10-08

I'm using the following to create a dynamic menu for repair jobs I'm running on remote servers:

Write-Host "`nCurrent Repair States:"
(Get-Job | Where-Object {$_.State -ieq 'Completed' -or $_.State -ieq 'Running' -and $_.Name -like "*-Repair"}) | Format-Table Name, State -HideTableHeaders

$jobList = Get-Job | Where-Object {$_.State -ieq 'Completed'-and $_.Name -like "*-Repair"}
Write-Host "Selectable Completed SCCM Client Repairs:`n"
Foreach ($menuItem in $jobList) {
    "  {0}.`t{1}" -f ($jobList.IndexOf($menuItem)   1), $menuItem.Name
}

$jobChoice = ''
while ([string]::IsNullOrWhiteSpace($jobChoice)) {
    $jobChoice = Read-Host "`nPlease choose the Machine by number"
    if ($jobChoice -inotin 1..$jobList.Count) {
        Write-Host
        Write-Host ('    Please try again ...') -Foreground Yellow
        Write-Host
                
        $jobChoice = ''
    }
}

This works great as long as there are zero or two or more jobs that meet the Where-Object criteria. Though once there is only one item found I get the following error:

Method invocation failed because [System.Management.Automation.PSRemotingJob] does not contain a method named 'IndexOf'.
At C:\repairCheck.ps1:7 char:5
      "  {0}.`t{1}" -f ($jobList.IndexOf($menuItem)   1), $menuItem ...
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidOperation: (:) [], RuntimeException
      FullyQualifiedErrorId : MethodNotFound

CodePudding user response:

Change this statement:

$jobList = Get-Job | Where-Object {$_.State -ieq 'Completed'-and $_.Name -like "*-Repair"}

to:

$jobList = @(Get-Job | Where-Object {$_.State -ieq 'Completed'-and $_.Name -like "*-Repair"})

The array subexpression operator (@()) will ensure that the value assigned to $jobList is always an array, regardless of whether the Get-Job | ... expression evaluates to 0, 1 or multiple job references.

  • Related