首页 > 解决方案 > 使用 PSRemotingJob 的动态菜单中的 IndexOf 错误

问题描述

我正在使用以下内容为我在远程服务器上运行的修复作业创建一个动态菜单:

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

只要有零个或两个或多个满足Where-Object标准的工作,这就会很有效。虽然一旦只找到一个项目,我就会收到以下错误:

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

标签: arrayspowershell

解决方案


更改此语句:

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

至:

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

数组子表达式运算符 ( @()) 将确保分配给的值$jobList始终是一个数组,无论Get-Job | ...表达式的计算结果是 0、1 还是多个作业引用。


推荐阅读