我有一个包含文件列表的文件夹“D:\ PROD \ transfert”。
我想编写一个Powershell脚本,列出文件并让用户选择一个,然后脚本将对所选文件执行操作。理想情况下,我希望将所选文件的路径存储在变量中。
这是想要的输出:
>Select a file :
[1] file1.zip
[2] file2.zip
[3] file3.zip
>
我现在能做的就是列出之前没有数字的文件:
Get-ChildItem C:\PROD\transfert | % { $_.FullName }
谢谢!
答案 0 :(得分:5)
除非您绝对需要控制台GUI,否则您可以使用Out-GridView
让用户选择,如下所示:
Get-ChildItem C:\PROD\transfert | Out-GridView -Title 'Choose a file' -PassThru | ForEach-Object { $_.FullName }
<强> 修改 强> ......并存储在变量中......
$filenames = @(Get-ChildItem C:\PROD\transfert | Out-GridView -Title 'Choose a file' -PassThru)
@()
包装器确保始终返回文件名数组(即使选择了一个文件或没有文件)。
(Passthru
依赖于您拥有PowerShell 3或更高版本)
编辑2
下面的选择菜单将改变显示类型,具体取决于是在控制台还是GUI(例如ISE)。我还没有通过WinRM进行测试,但是当通过普通的PowerShell控制台调用时,它不应该生成GUI。
$files = Get-ChildItem -Path C:\PROD\transfert -File
$fileChoices = @()
for ($i=0; $i -lt $files.Count; $i++) {
$fileChoices += [System.Management.Automation.Host.ChoiceDescription]("$($files[$i].Name) &$($i+1)")
}
$userChoice = $host.UI.PromptForChoice('Select File', 'Choose a file', $fileChoices, 0) + 1
# do something more useful here...
Write-Host "you chose $($files[$userChoice].FullName)"
请注意Get-ChildItem