Wednesday, March 25, 2015

PSTip : Open file and open folder dialog

Did you had issues whenever the users were expected to provide the full path for the file or folder to work on with a script?
Well, instead of asking them to type the path, you can use the Winforms API to choose the file/ folder. I have create couple of methods to add into my PS modules for using in this scenario.

Function Open-File
{
      param
      (
            [String] $Title = "Choose the file",
            [String] $Filter = "*.*",
            [String] $InitialDirectory = "C:\"
      )

      [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
      $dialog = New-Object System.Windows.Forms.OpenFileDialog
      $dialog.Title = $Title
      $dialog.Filter= $Filter
      $dialog.InitialDirectory = $InitialDirectory
      $result = $dialog.ShowDialog()
      if($result -eq [System.Windows.Forms.DialogResult]::OK)
      {
            $dialog.FileName
      }
      else
      {
            [String]::Empty
      }
}

Function Open-Folder
{
      [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
      $dialog = New-Object System.Windows.Forms.FolderBrowserDialog
      $dialog.RootFolder = "Desktop"
      $dialog.ShowNewFolderButton = $true
      $result = $dialog.ShowDialog()

      if($result -eq [System.Windows.Forms.DialogResult]::OK)
      {
            $dialog.SelectedPath
      }
      else
      {
            [String]::Empty
      }

}

No comments: