Using OpenFileDialog in PowerShell

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.

Advertisements
This entry was posted in Programming and tagged , , . Bookmark the permalink.

One Response to Using OpenFileDialog in PowerShell

  1. Pingback: Using OpenFileDialog in PowerShell | Powershell Faq

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s