0% found this document useful (0 votes)
26 views14 pages

How To Create An Open File - Folder Dialog Box With PowerShell - 4sysops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views14 pages

How To Create An Open File - Folder Dialog Box With PowerShell - 4sysops

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

How to create an open file/folder


dialog box with PowerShell
Home / Blog / How to create an open file/folder dialog box with PowerShell
4sysops - The online community for SysAdmins and DevOps

Adam Bertram Mon, Jun 11 2018 powershell, powershell beginner 36 

The open file/folder dialog box is a great way to receive input for your
scripts interactively. It provides a file browser that makes for a much more
user-friendly approach than merely prompting for a path. In this post I
show you how can use OpenFileDialog in your PowerShell scripts.

Ho
wr
Az
ChatGPT for IT admins: Trained with the latest IT content
Fu
Po
Try now! Ad

Author Recent Posts

Adam Bertram
Adam Bertram is a 20-year IT veteran, Microsoft MVP, blogger, and trainer.

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 1/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

When you're using a Windows application and need to provide input for a file or
folder, you've probably seen the standard open file dialog.

Allow end users execute PowerShell scripts without admin rights


Download System Frontier now! Ad

Ho
wr
Az
Fu
Po

Open file dialog

This dialog box is standard across lots of Windows applications. The software
you're using to invoke this dialog box uses a .NET assembly called
System.Windows.Forms with a class inside called OpenFileDialog. Did you know
you can get input to your PowerShell scripts this way too? Since PowerShell lies
directly on top of .NET, we can invoke any .NET class we need, which means we
can also bring up the open file dialog box.

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 2/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

To do this, we'll first need to load the System.Windows.Forms assembly manually


using the Add-Type cmdlet. Lots of .NET assemblies are typically loaded for you,
but in this case, we have to do it manually.

1. Add-Type -AssemblyName System.Windows.Forms

Once we've loaded the assembly, we can instantiate an OpenFileDialog object


using New-Object.
1. $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -
Property @{ InitialDirectory =
[Environment]::GetFolderPath('Desktop') }

You can see above that the OpenFileDialog class constructor has an
InitialDirectory argument. This tells the OpenFileDialog class which folder to dis-
play when the dialog box comes up. In this case, I have the dialog box to display
the desktop.

At this point, the dialog box will not display. We're just instantiating the object. To
show the dialog box, we'll have to use the ShowDialog() method.

1. $null = $FileBrowser.ShowDialog()

This will display the dialog box. I'm assigning the output of ShowDialog() to $null.
This is because the output does not return anything useful for our purposes. You
might expect the output to return the chosen file name, but it doesn't. The system
then stores the file information in the OpenFileDialog object itself.
1. PS C:\> $FileBrowser 
2.
3. CheckFileExists : True
Ho
4. Multiselect : False
wr
5. ReadOnlyChecked : False
Az
6. ShowReadOnly : False
Fu
7. SafeFileName : Thumbs.db
Po
8. SafeFileNames : {Thumbs.db}
9. AddExtension : True
10. CheckPathExists : True
11. DefaultExt :
12. DereferenceLinks : True
13. FileName : \\Mac\Home\Desktop\Thumbs.db
14. FileNames : {\\Mac\Home\Desktop\Thumbs.db}
15. Filter :
16. FilterIndex : 0
17. InitialDirectory : \\Mac\Home\Desktop
18. RestoreDirectory : False
19. ShowHelp : False
20. SupportMultiDottedExtensions : False
21. Title :
22. ValidateNames : True
23. CustomPlaces : {}

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 3/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

24. AutoUpgradeEnabled : True


25. Tag :
26. Site :
27. Container :

You can see above that the OpenFileDialog object now contains all the informa-
tion gathered from the file chosen.

The above example allows me to choose any file we'd like, but we also can limit
the input by file type too using the Filter property.

1. $FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -


Property @{
2. InitialDirectory = [Environment]::GetFolderPath('Desktop')
3. Filter = 'Documents (*.docx)|*.docx|SpreadSheet
(*.xlsx)|*.xlsx'
4. }
5. $null = $FileBrowser.ShowDialog()

Now when the dialog box displays, you can see below that the only options are to
choose between Word and Excel documents.

For more information about this method of receiving file location input from users,
refer to the Microsoft MSDN information. 

Ho
wr
Az
Fu
Po

36 COMMENTS

Leos Marek 5 years ago

Yes, by using the Title property, example below:

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 4/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{

InitialDirectory = [Environment]::GetFolderPath('Desktop')

Filter = 'Documents (*.docx)|*.docx|SpreadSheet (*.xlsx)|*.xlsx'


Title = 'Select files to open'

+6

REPLY

Sondre Sætervadet
5 years ago

Hey

The file i select when i can choose a file wont open when i press open

+2

REPLY

Nevor Yard 2 years ago

Try this: 

start $FileBrowser.filename
Ho
+1 wr
Az
REPLY
Fu
Po
David Figueroa
5 years ago

Sondre – the dialog is just going to give you the name of the file, and
that's it. It doesn't *do* anything with it, that is up to you and your code.
Your code needs to take the file and do whatever with it.

If you use a ShellExecute method or anything that will call the default
verbs, it will run whatever program is associated with that file type, using
the command string defined in the file association passing the file name
to that string. So.. if you pick a .docx, and use the default exec, it will
launch Word and feed in the file you picked. If there isn't a file
association for that type, you will get the Windows prompt to pick a
program to run for that file.

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 5/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

David F.

+4

REPLY

NameInUse 2 years ago

So how to use ShellExecute in this case to open the selected file??

REPLY

dunca
5 years ago

thanks man very very nice article, and good job

REPLY

Stevie
5 years ago

Great article – this just enhanced a script I wrote 10mins ago.



I'm immediately looking to see if there is a CreateFileDialog object type
too – excellent for those scripts which need output, and we don't want to Ho
hard-code paths if we can avoid it. wr
Az
0 Fu
REPLY Po

Aniket
5 years ago

Very good blog and helpful. Similarly how can we select folder path
instead of file??

Thanks in Advance 🙂

REPLY

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 6/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

David Figueroa
5 years ago

You just need to use the correct .Net class..

Add-Type -AssemblyName System.Windows.Forms


$dialog = [System.Windows.Forms.FolderBrowserDialog]::new()
$dialog.Description = 'This is a description'

$dialog.RootFolder = [System.Environment+specialfolder]::Desktop
$dialog.ShowNewFolderButton = $true
$dialog.ShowDialog()

$dialog.Dispose()

The documentation is at https://docs.microsoft.com/en-


us/dotnet/api/system.windows.forms.folderbrowserdialog?
view=netframework-4.8. 

David F.

+4

REPLY


Mir 2 years ago

Hi David Ho
I was looking for this for longtime. But I have one more questions. I am wr
Az
very new in this scripting world but learning… I am trying to create a
Fu
script that will install printer package onto remote machine. when I will Po
run the script it will open the dialog box to select the printer package. I
got it so far to select now how can I parse that to copy the selected file
to the remote machine. I know the copy part but wondering how to use
this dialog box part to select in the copy portion. I would appreciate your
answer if you can. Thanks a lot in advance.

REPLY

David Figueroa 2 years ago

The return of the dialog should be the folder path. If you want the file,
you need the FileBrowserDialog instead (almost exactly the same and it
returns the full file path). Does that answer the question?

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 7/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

David F.

+1

REPLY

Aniket Sonkusare
5 years ago

Thanks David… 🙂

I have used above code and it is working and I am able to select folder.

Facing one strange thing. Whenever I work in ISE, the select folder
dialogue box went to last open item in windows instead of popping up on
current window. But if I use powershell command line, dialogue box
popping up and I can select folder.

REPLY

David Figueroa
5 years ago


It'll be a function of where you call the dialog from. Some apps (like the
ISE) will remember the last folder you used, so, unless you specify a
root every time, it will go to your last place. Ho
wr
Glad it worked out for you though 🙂 Az
Fu
David F. Po

REPLY

BETOMBO Mariot
5 years ago

Very Usefull. Thanks

REPLY

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 8/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

Ségur marc
4 years ago

hello how I can select a Folder?

REPLY

David Figueroa
4 years ago

It's pretty much the exact same technique.. with a slightly different class.

https://docs.microsoft.com/en-
us/dotnet/api/system.windows.forms.folderbrowserdialog?view=netcore-
3.1

Coralon

REPLY

Denis 
4 years ago

Helpful article. Thanks. Ho


wr
Is there any method for tricking the OpenFileDialog into allowing me to Az
select a folder? Fu
Po
– I find the alternative [FolderBrowserDialog] far too awkward [I cannot
see the folder hierarchy while I'm browsing, I can't paste in a path to get
to where I want to go quickly, it's like peering through a keyhole]

+1

REPLY

Leos Marek 4 years ago

https://4sysops.com/archives/how-to-create-an-open-file-folder-dialog-
box-with-powershell/#comment-781675
file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 9/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

+1

REPLY

Denis
4 years ago

Leos,

That does not address my question at all.

I asked about the OpenFileDialog .

I stated perfectly clearly that I did not want to use the


FolderBrowserDialog.

Yet you post a link to a post about the FolderBrowserDialog .

Denis

+1

REPLY

Leos Marek 4 years ago

Then the answer is no. OpenFileDialog does not allow that.



+1

REPLY
Ho
wr
Denis Az
4 years ago Fu
Po
The best I've been able to come up with is very much a workaround.

Add-Type -AssemblyName system.Windows.Forms

$SetBackupLocation = New-Object System.Windows.Forms.SaveFileDialog


$SetBackupLocation.InitialDirectory = [Environment]::GetFolderPath('Desktop')
$SetBackupLocation.Title = 'Choose folder - Enter a folder so it is selected in the

NavPane then click on Save'


$SetBackupLocation.FileName = 'Location'
$rc = $SetBackupLocation.ShowDialog()

if ($rc -eq [System.Windows.Forms.DialogResult]::OK)

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 10/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

$BackupLocation = $SetBackupLocation.FileName
$BackupLocation = $BackupLocation.Replace('Location', "")
}

echo $BackupLocation
Pause #To look at the result

This came from Getting the file location using openfiledialog in


powershell – TechNet

As noted in the dialog title, the code returns the path of the folder that is
selected in the Navigation Pane.

I also found A better folderbrowserdialog – Sapien Forums but I could


not get it to run.

Denis

+2

REPLY

Leos Marek 4 years ago 

Yeah I just wanted to write that you could select a file inside that folder Ho
and adapt the script to get the folder path from the file.. 🙂 wr
Az
0 Fu
REPLY Po

Denis 4 years ago

The posted code, which uses the SaveFileDialog, does not require a file
to be selected.

There will be cases where an empty folder is wanted so nothing based


on selecting a file could be used.

Denis

REPLY

Leos Marek 4 years ago


file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 11/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

It was just an example, no need to catch every word 🙂 Seems that you
already have a solution for the topic which is great.

Cheers

REPLY

Joe Stutter 2 years ago

I got the code you mentioned here “I also found a better folder browser
dialog – Sapien Forums but I could not get it to run. to work. The issue is
on line 122. The original looks like this:

for (int i = 1; i < names.Length; ++i) {


type = type.GetNestedType(names, BindingFlags.NonPublic);
}

it should be:

for (int i = 1; i < names.Length; ++i) {


type = type.GetNestedType(names[i], BindingFlags.NonPublic);
}


names is an array and it is missing the counter [i] in the code.
Ho
0
wr
REPLY Az
Fu
Po
asdasda
4 years ago

Now show how to open specific location not environment folder!

+3

REPLY

Jason Spencer
2 years ago

How would I handle if the user decides to click “cancel” on the open file
dialog box? I’m guessing some kind of If / Else statement – but what
condition can I check for?
file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 12/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

Right now, my code is expecting a valid file to be selected, and when I


hit cancel, it tries to run off a $null expressioned Filebrowser.filename.

REPLY

David Figueroa
2 years ago

You pretty much answered your own question. 🙂 Check if your result is
$null first, and handle it as you need.

David F.

REPLY

Simmons 1 year ago

I tried if ($fileBrowser -eq $null) { Exit } but that doesn’t work. how do
you capture a cancel?

REPLY

David Figueroa 1 year ago
Ho
That may or may not work.. you normally check along the lines of
wr
“$result = $fbdialog.ShowDialog(); if ($null -eq $result) { #cancel pushed Az
}” Fu
Po
David F.

REPLY

Joshua Szanto
1 year ago

Execution hangs up on usage of ShowDialog() under PowerShell 7 for


me; it just stalls out. Another colleague does not have the same issue in
PowerShell 7. Works fine in PowerShell 5.1 though. Any ideas? Been
searching high and low and not sure why it stalls out upon executing
ShowDialog() line in PoSh7.

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 13/14
21/10/2024 16:38 How to create an open file/folder dialog box with PowerShell – 4sysops

REPLY

David Figueroa
12 months ago

You might check out this article:


https://blog.netnerds.net/2016/01/showdialog-sucks-use-
applicationcontexts-instead/
Chrissy (author of DBATools) recommends that people use

$appContext = New-Object System.Windows.Forms.ApplicationContext


[void][System.Windows.Forms.Application]::Run($appContext)

instead of ShowDialog()
That might work for you?

David F.

REPLY


WindowsUpdatePreventer
Ho
wr
Az
Fu
Po

file:///C:/Users/vpn/Desktop/How to create an open file_folder dialog box with PowerShell - 4sysops.mhtml 14/14

You might also like