2017-04-18 37 views
0

我正在为一家公司编写一个伪搜索引擎,让他们找到一些歌曲,然后选择它们并与它们一起做东西。我能够显示和选择内容,直到返回给我只有一首歌。而当你试图选择一首歌曲返回的错误是:

无法选择返回1 of 1 powershell脚本

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" 

的最终目标是要当只有一首歌曲被返回时能够选择单首歌曲。感谢您的任何帮助!

回答

2

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

另一个问题是$ 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*) 

或者你可以问

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

我也很小心使用写主机前检查$项目。如果你查看它,你可以挖掘兔子洞,但通常Write-Host不是你应该使用的输出选择。

+0

谢谢!我决定检查$ Items,它现在可以工作!我也改变了这个变量 –