Selecting a file in bat file using OpenFileDialog

This article shows how to program OpenFileDialog window in a batch file i.e. BAT or CMD. It will be more convenient for users to be able to select a file with mouse in graphical dialog box rather than typing exact path and name in the command line.

openfiledialog-bat-1
openfiledialog-bat-2
openfiledialog-bat-3
previous arrow
next arrow

How to create OpenFile dialog box in bat file

As there are no built-in dialog boxes in bat files I’m going to use an external software component.

That’s PowerShell which nowadays is always pre-installed on Windows giving access to System.Windows.Forms.OpenFileDialog component:

PowerShell script to display OpenFIle dialog box

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | out-null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = "C:\"
$OpenFileDialog.filter = "Excel workbooks (*.xlsx)|*.xlsx|All files (*.*)|*.*"
$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename

This snippet sets file type filter (either Excel workbooks or all files for example), opens dialog box and accept user choice returning OK followed by file name:

OK
C:\Users\user\Documents\calendar 2020.xlsx

If no file was selected just Cancel will be returned.

Cancel

How to call PowerShell script from bat file and process returned text

Command line to run the script is

powershell -executionpolicy bypass -file openfiledialog-xlsx.ps1

Bat file should run the script and process its output line-by-line.
If a file was selected %filename% variable will contain path and name of the selected file otherwise the variable will be empty.

@echo off
for /F "tokens=* usebackq" %%a in (`powershell -executionpolicy bypass -file openfiledialog-xlsx.ps1`) do if not "%%a" == "Cancel" if not "%%a" == "OK" set filename=%%a 
if not "%filename%"=="" echo %filename%

Bat file with embedded PowerShell script

It is actually rather creating PowerShell script dynamically than usual embedding.
Anyway it eliminates keeping extra script file (PowerShell). Also it allows to set initialDirectory and filter values within bat file.

Bat file

This bat file firstly creates PowerShell script. Values for OpenFileDialog properties can be set dynamically.
After that the bat file runs the created script and processes its output.
Finally the bat file deletes the script because it is not needed anymore and prints file name if a file was selected.

@echo off

set ps_fn=ofd.ps1
echo [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") ^| out-null > %ps_fn%
echo $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog >> %ps_fn%
echo $OpenFileDialog.initialDirectory = "%USERPROFILE%\Downloads" >> %ps_fn%
echo $OpenFileDialog.filter = "Excel workbooks (*.xlsx)|*.xlsx|All files (*.*)|*.*" >> %ps_fn%
echo $OpenFileDialog.ShowDialog() >> %ps_fn%
echo $OpenFileDialog.filename >> %ps_fn%

for /F "tokens=* usebackq" %%a in (`powershell -executionpolicy bypass -file %ps_fn%`) do if not "%%a" == "Cancel" if not "%%a" == "OK" set filename=%%a
del %ps_fn%

if not "%filename%"=="" echo %filename%

OpenFileDialog properties

initialDirectory property can be a folder in user’s profile (“%USERPROFILE%\Downloads“), directory of bat file (“%~dp0“) or current directory (“%cd%“).

filter property can be configured depending on file type. The example above shows fiter for Excel workbook XLSX or all files..

Here are examples for txt and csv files. .

Text files (*.txt)|*.txt|All files (*.*)|*.*
CSV files (*.csv)|*.csv|All files (*.*)|*.*

Frequently asked questions

Does it support long file path and name with spaces?

Yes, the script processes correclty file names containing spaces.

Does it allow to select multiple files at once?

No, this version for selecting one file only.

Does it support Unicode characters in file path or name?

No, any character that does not fall in ANSI character set will be converted to question mark.
Actually PowerShell script does support Unicode but its output is converted to ANSI within bat file.

Files to download

See also

System.Windows.Forms.OpenFileDialog class

More PowerShell scripts

More bat files


Comments

8 responses to “Selecting a file in bat file using OpenFileDialog”

  1. Thomas Stein Avatar
    Thomas Stein

    You should ALWAYS escape parenthesis in echoed lines with a caret, so replace “(” by “^(” and “)” by “^)”. You will see the difference as soon you enclose any other parenthesis, like inside a multi-lined if-statement.

    1. Thomas Stein Avatar
      Thomas Stein

      This one includes German Umlautes, spaces and many other special characters:

      @echo off
      chcp 1252 >nul
      set ps_fn=”%temp%\ofd.ps1″
      > %ps_fn% (
      echo [System.Reflection.Assembly]::LoadWithPartialName^(“System.windows.forms”^) ^| out-null
      echo $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
      echo $OpenFileDialog.initialDirectory = “%USERPROFILE%\Downloads”
      echo $OpenFileDialog.filter = “Excel workbooks ^(*.xlsx^)|*.xlsx|All files ^(*.*^)|*.*”
      echo $OpenFileDialog.ShowDialog^(^)
      echo $OpenFileDialog.filename
      )

      for /F “tokens=* usebackq” %%a in (`powershell -executionpolicy bypass -file %ps_fn%`) do if not “%%a” == “Cancel” if not “%%a” == “OK” set “filename=%%a”
      del /f/q %ps_fn%

      if defined filename echo “%filename%”

    2. Microsoft recommends to use a caret (^) to display a pipe (|), ampersand (&), redirection character (< or >), or exclamation mark (!) but no parenthesis.
      See https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/echo
      microsoft-echo-caret
      And, when I run echo with a caret before parenthesis I get caret echoed:
      echo-caret-parenthesis

  2. Swapnanil Kayal Avatar
    Swapnanil Kayal

    How to take filenames with space?

    1. Good question, thanks for posting!
      The arguments for FOR command needs to be corrected as shown below so %%a variable will contain full string from openfiledialog.ps1:

      for /F "tokens=* usebackq"... 

      I just updated the code in the post.

      1. the file picker works like a charm, but the space-character adjustment does not work for me

        1. edit – needed to put %%a at the end of the line in brackets, so its
          for /F “tokens=* usebackq” %%a in (`powershell -executionpolicy bypass -file openfiledialog.ps1`) do if not “%%a” == “Cancel” if not “%%a” == “OK” set filename=”%%a”

          1. For me it reads correctly file names with spaces and needs no extra quotes.
            Above there is a screenshot of bat file output when file name with spaces. was selected
            I also made bat files available for downloading so it is possible to test them.

Leave a Reply

Your email address will not be published. Required fields are marked *