Using Open File Dialogs

by Feb 14, 2013

To spice up your scripts, PowerShell can use the system open file dialog, so users could easily select files to open or to parse. Here's the code to open the dialog and evaluate the dialog results:

$dialog = New-Object -TypeName System.Windows.Forms.OpenFileDialog

$dialog.AddExtension = $true
$dialog.Filter = 'PowerShell-Script (*.ps1)|*.ps1|All Files|*.*'
$dialog.Multiselect = $false
$dialog.FilterIndex = 0
$dialog.InitialDirectory = "$HOME\Documents"
$dialog.RestoreDirectory = $true
$dialog.ShowReadOnly = $true
$dialog.ReadOnlyChecked = $false
$dialog.Title = 'Select a PS-Script'

$result = $dialog.ShowDialog()

if ($result = 'OK')
{
    $filename = $dialog.FileName
    $readonly = $dialog.ReadOnlyChecked
    if ($readonly) { $mode = 'read-only' } else { 'read-write' }
    "I could now open '$filename' as $mode and do something..."
} 

Note that the dialog requires the STA mode. The code runs fine in PowerShell 3.0 and in PowerShell 2.0 ISE. It will crash PowerShell 2.0 consoles unless you start them with the parameter -STA.

Note also that the dialog may occasionally appear behind the ISE editor, so if the editor seems to not respond, check to see whether the dialog is waiting for your input in the background.

Twitter This Tip! ReTweet this Tip!