2017-04-18 64 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,它現在可以工作!我也改變了這個變量 –