Powershell列出文件并让用户选择一个

kyo*_*ori 2 powershell

我有一个包含文件列表的文件夹"D:\ PROD\transfert".

我想编写一个Powershell脚本,列出文件并让用户选择一个,然后脚本将对所选文件执行操作.理想我希望所选文件的路径存储在变量中.

这是想要的输出:

>Select a file :
[1] file1.zip
[2] file2.zip
[3] file3.zip
>
Run Code Online (Sandbox Code Playgroud)

我现在能做的就是列出没有数字的文件:

Get-ChildItem C:\PROD\transfert | % { $_.FullName }
Run Code Online (Sandbox Code Playgroud)

谢谢 !

Tec*_*pud 6

除非您绝对需要控制台GUI,否则您可以使用它Out-GridView来让用户选择,如下所示:

Get-ChildItem C:\PROD\transfert | Out-GridView -Title 'Choose a file' -PassThru | ForEach-Object { $_.FullName }
Run Code Online (Sandbox Code Playgroud)

编辑 ...并存储在变量中......

$filenames = @(Get-ChildItem C:\PROD\transfert | Out-GridView -Title 'Choose a file' -PassThru)
Run Code Online (Sandbox Code Playgroud)

所述@()包装可以确保文件名的阵列总是返回(即使选择一个文件或没有文件).

(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)"
Run Code Online (Sandbox Code Playgroud)

注意由多少文件返回 Get-ChildItem