Using the OpenFile Dialog

by Aug 13, 2014

PowerShell 3.0 and newer

Here’s a quick function that works both in the ISE editor and the PowerShell console in PowerShell 3.0 and above): Show-OpenFileDialog.

function Show-OpenFileDialog
{
  param
  (
    $StartFolder = [Environment]::GetFolderPath('MyDocuments'),

    $Title = 'Open what?',
    
    $Filter = 'All|*.*|Scripts|*.ps1|Texts|*.txt|Logs|*.log'
  )
  
  
  Add-Type -AssemblyName PresentationFramework
  
  $dialog = New-Object -TypeName Microsoft.Win32.OpenFileDialog
  
  
  $dialog.Title = $Title
  $dialog.InitialDirectory = $StartFolder
  $dialog.Filter = $Filter
  
  
  $resultat = $dialog.ShowDialog()
  if ($resultat -eq $true)
  {
    $dialog.FileName
  }
}

It opens a OpenFile dialog. The user can select a file, and the selected file is returned to PowerShell. So next time your script needs to open a CSV file, you may want to use the additional luxury of opening a selection dialog.

Twitter This Tip! ReTweet this Tip!