无法 select return 1 个 powershell 脚本中的 1 个

Not able to select return 1 of 1 powershell script

我正在为一家公司编写一个伪搜索引擎,让他们找到一些歌曲,然后 select 并用它们做一些事情。我能够显示 select 内容,直到 return 只给我一首歌。当您尝试 select 那一首歌时 returned 的错误是:

Unable to index into an object of type System.IO.FileInfo.
At C:\Users\adammcgurk\Documents\WorkOnSearch.ps1:83 char:20
+$Selected = $Items[ <<<< $Input - 1]
  + CategoryInfo              : InvalidOperation: (0:Int32) [], RuntimeException
  + FullyQualifiedErrorId     : CannotIndex

这是有问题的代码部分:

$SearchInput = Read-Host "Enter song name here:"
$Items = Get-ChildItem C:\Users\adammcgurk\Desktop\Songs -Recurse -Filter *$SearchInput*
$Index = 1
$Count = $Items.Count
foreach ($Item in $Items) {
    $Item | Add-Member -MemberType NoteProperty -Name "Index" -Value $Index
    $Index++
}
$Items | Select-Object Index, Name | Out-Host
$Input = Read-Host "Select an item by index number (1 to $Count)"
$Selected = $Items[$Input - 1]
Write-Host "You have selected $Selected"

最终目标是在只有一首 returned 时能够 select 单曲。感谢您的帮助!

一些观察,您使用 $input 作为变量名,但这是一个未正确使用的自动变量。 (get-help about_automatic_variables) 更改变量的名称。

另一个问题是 $Items 可能是也可能不是数组,但您正试图以任何一种方式对其进行索引。您可以在创建时将 $Items 显式转换为数组

#This will ensure that the return value is an array regardless of the number of results
$Items = @(Get-ChildItem C:\Users\adammcgurk\Desktop\Songs -Recurse -Filter *$SearchInput*)

或者您可以在询问之前查看 $items

if($Items -is [System.Array]){
    #Handle choice selection
}else{
    #only one object
    $Items
}

我也会小心使用 Write-Host。如果您查找它,您可以深入挖掘兔子洞,但通常 Write-Host 不是您应该使用的输出选择。