arrays - 使用 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
解决方案
更改此语句:
$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 还是多个作业引用。
推荐阅读
- r - 如何修复 Rcpp 中内联函数的未定义引用
- windows - 运行时 System.DLLNotFoundException(从 Visual Studio 2017 开始 - x86,调试)
- openid - Symfony 4:如何使用 GuardAuthenticator 实现 OpenId Connect?
- ios - 具有丰富内容的 iOS 推送通知 - 我可以防止通知被点击吗?
- ruby-on-rails - 为什么我的 Heroku 管道审查应用程序无法构建并出现错误:ActiveSupport::EncryptedFile::MissingKeyError
- java - sessionRegistry.getAllPrincipals() 始终为空
- visual-studio-code - 如何在 vs 代码上启用 Suitescript IntelliSense?
- javascript - 为什么当我创建函数的新实例时函数内部的代码会运行
- python - 应用操作以连接数据帧重新调整中的某些行无
- bootstrap-4 - 为什么 align-items-center 在 Bootstrap4 中不起作用?