How many scripts have you had to had a line in that declares a file path? How many times has that path changed? Some scripters like to use a host prompt to ask for the variable, or they declare it in a parameter in the command-line… me, I like to fancy things up since its just me using the script and I don’t mind the extra 2 seconds it takes the script to load up a OpenFileDialog box. Just keep in mind this means you’ll need to load PowerShell in STA mode for the .NET forms to load! Enjoy the snippet.
Function Get-FileLoc ($initialDirectory) { [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog $OpenFileDialog.initialDirectory = $initialDirectory $OpenFileDialog.filter = "Excel (*.xlsx)| *.xlsx|Excel (*.xls)| *.xls|All files (*.*)|*.*" $OpenFileDialog.ShowDialog() | Out-Null $OpenFileDialog.filename $OpenFileDialog.ShowHelp = $true }
And just to clear up the “Excel (*.xlsx)| *.xlsx|Excel (*.xls)| *.xls|All files (*.*)|*.*” part for you all, that is the line used to populate the drop down for file types. Since I work with Excel files a lot, that is what I show, but it can be changed to suit whatever file types you want to list by putting a pipe between list items.
Hat hip to Scripting Guy! for this one.
Pingback: Using OpenFileDialog in PowerShell | Powershell Faq