Using OpenFile Dialog

by Nov 1, 2010

You can use this code to open a standard OpenFile dialog in your PowerShell scripts:

[System.Reflection.Assembly]::LoadWithPartialName("") | Out-Null
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog = New-Object System.Windows.Forms.OpenFileDialog
$dialog.DefaultExt = '.ps1'
$dialog.Filter = 'PowerShell-Skripts|*.ps1|All Files|*.*'
$dialog.FilterIndex = 0
$dialog.InitialDirectory = $home
$dialog.Multiselect = $false
$dialog.RestoreDirectory = $true
$dialog.Title = "Select a script file"
$dialog.ValidateNames = $true

To run the selected script, use this line instead:

& $dialog.FileName

Important note: Dialogs only work correctly when you launch PowerShell with the -STA option! So before you enter and run the code, be sure to open the correct PowerShell environment:

Powershell -sta

Twitter This Tip!
ReTweet this Tip!