Advertisement
Lee_Dailey

function Show-SelectFileDialog

Oct 31st, 2017
1,601
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function Show-SelectFileDialog
  2.     {
  3.     [CmdletBinding()]
  4.  
  5.     Param
  6.         (
  7.         [Parameter (
  8.             Mandatory,
  9.             Position = 0
  10.             )]
  11.             [ValidateNotNullOrEmpty()]
  12.             [string]
  13.             $TopDir,
  14.  
  15.         # extension examples = "*", "*.*", "log", ".txt", "*.csv"
  16.         [Parameter (
  17.             Position = 1
  18.             )]
  19.             [string]
  20.             $FileType = '*.*'
  21.         )
  22.  
  23.     switch ($FileType)
  24.         {
  25.         # extensionless files can't be shown on their own
  26.         #    so they are included with the ALL files group
  27.         {$_ -in ('.', '*.', '', '*', '.*', '*.*')}
  28.             {
  29.             $FilterString = "All files (*.*)|*.*"
  30.             break
  31.             }
  32.         {$_.StartsWith('*.')}
  33.             {
  34.             $TypeName = $_.TrimStart('*.').ToUpper()
  35.             $FilterString = "$TypeName files ($FileType)|$FileType|All files (*.*)|*.*"
  36.             break
  37.             }
  38.         {$_.StartsWith('.')}
  39.             {
  40.             $TypeName = $_.TrimStart('.').ToUpper()
  41.             $FilterString = "$TypeName files (*$FileType)|*$FileType|All files (*.*)|*.*"
  42.             break
  43.             }
  44.         default
  45.             {
  46.             $TypeName = $_.ToUpper()
  47.             $FilterString = "$TypeName files (*.$FileType)|*.$FileType|All files (*.*)|*.*"
  48.             }
  49.         }
  50.  
  51.     [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") |
  52.         Out-Null
  53.     $SelectFileDialog = New-Object System.Windows.Forms.OpenFileDialog
  54.     $SelectFileDialog.InitialDirectory = $TopDir
  55.     $SelectFileDialog.Filter = $FilterString
  56.     $SelectFileDialog.Title = 'Please select a file and then click [Open]'
  57.  
  58.     # finally show the dialog
  59.     $SelectFileDialog.ShowDialog() |
  60.         Out-Null
  61.  
  62.     # send the filename to output
  63.     $SelectFileDialog.FileName
  64.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement