Using PowerShell and .NET Framework Class to Open a File Dialog Box

Using PowerShell script to open a file dialog:

[reflection.assembly]::loadwithpartialname(“System.Windows.Forms”) | Out-Null
$openFile = New-Object System.Windows.Forms.OpenFileDialog
$openFile.Filter = “txt files (*.txt)|*.txt|All files (*.*)|*.*” 
If($openFile.ShowDialog() -eq “OK”
   get-content $openFile.FileName

ShowDialog() returns a DialogResult Enumeration of either an OK or Cancel. Since you can’t click OK in the dialog until you pick a file, you also get some validation in the process. Once the file is selected and the user clicks the Open button in the dialog, you pass the path to the Get-Content cmdlet on the last line and resume your PowerShell script.



Leave a Reply

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

You are commenting using your 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