Skip to content

Use file open dialog in PowerShell


When creating interactive scripts it is nice to select files with the file open dialog instead to type in the complete path. Use this code

Add-Type -AssemblyName | Out-Null

        $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
        $OpenFileDialog.Multiselect = $True
        $OpenFileDialog.Filter = "All files (*.*)| *.*"
        # important if show jelp is not set to true the display of
  # the dialog may fail. The dialog is displayed in the ISE 
 # but when running from commandline it neve pops up
        $OpenFileDialog.showHelp = $true
        $OpenFileDialog.ShowDialog() | Out-Null

        foreach($fullFilePath in $OpenFileDialog.FileNames)
            #or do something usefull               

From → file, powershell

  1. Works as advertised, I intended to use this logic in a set of scripts i’ve created. THanks for your help. This post is still very helpful!

  2. I have a curiosity maybe someone can confirm for me what is going on. Copy and paste the following code into a powershell_ise.exe shell and execute.

    [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”);
    write-host “Running Function Browse for Files”;
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog;
    $OpenFileDialog.filter = “All files (*.*)| *.*”;
    $OpenFileDialog.Multiselect = $True;
    $OpenFileDialog.Title = “Files to Process:”;
    $OpenFileDialog.SupportMultiDottedExtensions = $True;

    The file selection dialog shows up as expected right?

    OK now try this open a run dialog (windows key + letter “R”)
    Type in: powershell.exe -ExecutionPolicy Unrestricted

    Now paste the same code in as above and hit enter. The dialog never shows up for me, and the powershell prompt never returns. I suspect the window has opened somewhere, but is not able to interact with my currently logged on session. Is there any way to fix this so I get the same behavior on powershell.exe as I do with powershell_ise.exe. I don’t want to have to install and open the ISE on every computer I intend to run this on.

    • Nevermind, I just read your comment in the code to enable the help. For whatever reason, that works!!

  3. Trotz permalink

    Much thanks

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 )

Google+ photo

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


Connecting to %s

%d bloggers like this: