Powershell OpenFileDialog


This is my preferred version of a function for calling a Windows GUI OpenFileDialog.

Adding a few GUI elements can be the difference between a script for your own use, and a sharable tool that people with less experience (or fear of CLI) can use.

This function invokes the standard .NET System.windows.forms tools within a PowerShell context.


Function Get-FilesFromDialog()
{  
 Param(
    [Parameter(Mandatory=$False)][String[]]$myInitialDirectory = $env:USERPROFILE,
    [Parameter(Mandatory=$False)][String[]]$myTitle = "Open File",
    [Parameter(Mandatory=$False, )][String[]]$myFilterString = ""

 )

 [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null

 $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
 $OpenFileDialog.initialDirectory = $myInitialDirectory
 $OpenFileDialog.filter = "$myFilterString" + “All files (*.*)| *.*”
 $OpenFileDialog.Multiselect = $true;
 $OpenFileDialog.Title = $myTitle;
 $OpenFileDialog.ShowDialog() | Out-Null
 $OpenFileDialog.filenames
}


(Compatible with Windows 7 and later)

This function is based on the template provided by The Scripting Guys in 2009, with a few targeted changes.

This version is designed for:

  • selecting multiple files and returns a list of the names.
  • parameterized inputs so that it can be easily inserted into larger scripts
    • effective default values for those parameter


{Design choices and usage examples will follow. }




Comments

Popular posts from this blog

Default Browser - set url association with PowerShell

LINQ within a foreach()

Rules of Automation