Skip to content

Folder or file browser dialogues in PowerShell

G28th July 2016

C8 Comments

TPowerShell, Windows

Make life easy for the users of your scripts: Rather then entering file/folder paths at the command line, let them select from a GUI dialogue box.

When designing PowerShell scripts, I have often found it useful to incorporate a file or folder dialogue to select files or folders. These make the selection of files or folders easy for users and prevent mistakes being made in file paths.

I have listed three PowerShell code snippets which I have found useful in developing PowerShell scripts that require a GUI folder or file selection in order to undertake a function:

  • A folder browser dialogue box
  • A file browser dialogue box (with file multiselect enabled)
  • A file browser dialogue box (for the selection of a single file)

Folder Browser Dialogue Box

The following script, which is based on the work of Frode F., can be used to bring up a Windows Folder Browser Dialogue when running a PowerShell script. Whilst there are many solutions to generating a Folder Browser Dialogue box, most of these cannot cope when the user presses “Cancel”. Either the script will produce error code and hang or otherwise crash PowerShell. In my view, this inelegant response is unacceptable.

A Windows folder browser dialogue box initiated in PowerShell.

A Windows folder browser dialogue box initiated in PowerShell.

The following code will test whether “OK” was pressed (ie a folder path was chosen) and then execute some code. If “Cancel” is pressed, a confirmation dialogue will pop up and check whether the user intended cancelling. If they did, the program will elegantly close. If not, the user will be returned to the Folder Browser Dialogue and given another opportunity to select a folder location.

Screen capture of dialogue box which reads "You pressed cancel. Would you like to try again?"

The PowerShell script will check whether the user intended pressing “Cancel” and either return them to the programme or close the application.

The folder location is stored in PowerShell as $browse.SelectedPath.

function Find-Folders {
    [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
    [System.Windows.Forms.Application]::EnableVisualStyles()
    $browse = New-Object System.Windows.Forms.FolderBrowserDialog
    $browse.SelectedPath = "C:\"
    $browse.ShowNewFolderButton = $false
    $browse.Description = "Select a directory"

    $loop = $true
    while($loop)
    {
        if ($browse.ShowDialog() -eq "OK")
        {
        $loop = $false
		
		#Insert your script here
		
        } else
        {
            $res = [System.Windows.Forms.MessageBox]::Show("You clicked Cancel. Would you like to try again or exit?", "Select a location", [System.Windows.Forms.MessageBoxButtons]::RetryCancel)
            if($res -eq "Cancel")
            {
                #Ends script
                return
            }
        }
    }
    $browse.SelectedPath
    $browse.Dispose()
} Find-Folders

As indicated in the above code, a number of variables can be customised including $browse.SelectedPath which will nominate a starting directory and $browse.ShowNewFolderButton which will allow a “New Folder” button to be added.

Should there be a desire to start the Folder Dialoge at “My Computer”, replace $browse.SelectedPath = "C:\" with $browse.RootFolder = [System.Environment+SpecialFolder]'MyComputer'.

File Browser Dialogue Box (with Multiselect)

The next script will enable a user to select multiple files from a dialogue box in PowerShell and then have something done to each of them whilst ignoring the others.

Screen capture of a Windows File Browser Dialogue Box

A Windows file browser dialogue box initiated in PowerShell

In the example below, the user can select from .jpg or .png files but this can be changed to other file types or otherwise removed if desired. The function that the script is going to perform will dicate what file types should be targeted. Further guidance about grouping files is available from the Microsoft Developer Network website.

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    Multiselect = $true # Multiple files can be chosen
	Filter = 'Images (*.jpg, *.png)|*.jpg;*.png' # Specified file types
}
 
[void]$FileBrowser.ShowDialog()

$path = $FileBrowser.FileNames;

If($FileBrowser.FileNames -like "*\*") {

	# Do something before work on individual files commences
	$FileBrowser.FileNames #Lists selected files (optional)
	
	foreach($file in Get-ChildItem $path){
	Get-ChildItem ($file) |
		ForEach-Object {
		# Do something to each file
		}
	}
	# Do something when work on individual files is complete
}

else {
    Write-Host "Cancelled by user"
}

File Browser Dialogue Box (Single File)

From the above script, only minor changes are required in order to remove the multi-select function an apply a script to a single file selected from a file browser dialogue box:

Add-Type -AssemblyName System.Windows.Forms
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
    Multiselect = $false # Multiple files can be chosen
	Filter = 'Images (*.jpg, *.png)|*.jpg;*.png' # Specified file types
}
 
[void]$FileBrowser.ShowDialog()

$file = $FileBrowser.FileName;

If($FileBrowser.FileNames -like "*\*") {

	# Do something 
	$FileBrowser.FileName #Lists selected files (optional)
	
}

else {
    Write-Host "Cancelled by user"
}
   

Comments:

8 responses to “Folder or file browser dialogues in PowerShell”

  • Written by Stepan on 5 October 2016:

    We Can Also Use ‘Long Path Tool’ To Shorten The File Name.

  • Written by Pankaj on 27 March 2017:

    Great, It was helpful.

  • Written by benschaNoob on 6 March 2018:

    at first a big thank you for your script! as a Nooby sites like this are very usefull!

    i have a small issue to use the variable $browse.SelectedPath, if i put this variable to output to a textbox, i only receive “.SelectedPath”. i’m also not able to use this variable for a Copy-Item $MySource $browse.SelectedPath

    may anybody give me a hint how i have to use the variable?

    thx

    • Written by nknk on 24 March 2018:

      i have a small issue to use the variable $browse.SelectedPath, if i put this variable to output to a textbox, i only receive “.SelectedPath”. i’m also not able to use this variable for a Copy-Item $MySource $browse.SelectedPath

      You may use """$($browse.SelectedPath)"""

  • Written by Guilherme Cruz on 6 April 2018:

    Excellent!. Exactly what I was searching for.

  • Written by Mike on 15 December 2018:

    Great Thanks – works like a acharm ! nice & easy

  • Written by SW on 9 January 2019:

    This script is great and exactly what I was looking for. However, I do have one issue.

    I’m new to powershell, so forgive me if I’m misunderstanding this, but this is my issue.

    I have used this script to populate a text box with the folder path. I have added a click event that calls this function which allows me to browse to a new path and re-populate the text box with the newly selected path. This works great. However, if you press Cancel to the dialog, it prompts you to Retry or Cancel. Pressing cancel return me to the main form, but the text box is blanked out.

  • Written by Chris on 20 January 2019:

    How can i use the interface shown in “File Browser Dialogue Box (with Multiselect)” in order to select folder(s) instead of files? I seem to be stuck with using “System.Windows.Forms.FolderBrowserDialog” which has no ‘navigation URL bar’ for lack of a better description like the one shown in your example for files does.

Have your say:

The following HTML is permitted:
<a href="" title=""> <b> <blockquote cite=""> <code> <em> <i> <q cite=""> <strike> <strong>

Comments will be published subject to the Editorial Policy.