I have a folder "D:\PROD\transfert" containing a list of files.
I want to write a Powershell script that will list the files and let the user chose one, the script will then perform actions on the selected file. Idealy I want the path of the selected file to be stored in a variable.
Here is the output wanted :
>Select a file :
[1] file1.zip
[2] file2.zip
[3] file3.zip
>
All i can do right now is listing the files with no number before :
Get-ChildItem C:\PROD\transfert | % { $_.FullName }
Thanks !
Unless you absolutely need a console GUI, you could you can use Out-GridView to let a user choose, like this:
Get-ChildItem C:\PROD\transfert | Out-GridView -Title 'Choose a file' -PassThru | ForEach-Object { $_.FullName }
EDIT ...and to store in a variable...
$filenames = @(Get-ChildItem C:\PROD\transfert | Out-GridView -Title 'Choose a file' -PassThru)
The @() wrapper ensures an array of filenames is always returned (even if one file or no files are chosen).
(the Passthru relies on you having PowerShell 3 or greater)
EDIT 2
The choice menu below will alter the display type, depending on whether in a console or GUI (e.g. ISE). I haven't tested over WinRM, but it shouldn't spawn a GUI when called via a normal PowerShell console.
$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)"
Be careful of how many of files are returned by the Get-ChildItem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With