2017-04-18 5 views
0

私は会社の疑似検索エンジンを作成しています。私は戻って私にただ一つの曲を与えるまでコンテンツを表示し、選択することができます。あなたはその1曲を選択しようとすると返されるエラーは、次のとおりです。

1個のpowershellスクリプトのリターン1を選択できません

$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" 

最終的な目標はことです:

ここ
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 

は、問題のコードの一部です。 1つだけが返されたときに1つの曲を選択することができます。何か助けてくれてありがとう!

答えて

2

いくつかの観察では、$ inputを変数名として使用していますが、これは正しく使用されていない自動変数です。 (get-help about_automatic_variables)変数の名前を変更します。

もう1つの問題は、$ 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をチェックすることにしました。私も変数を変更しました –

関連する問題