FileOpen und FileSave Dialoge mit Powershell

Da man mit Powershell auch die Windows API ansprechen kann, lässt sich auch ein FileOpen oder FileSave Dialog mit geringem Aufwand erstellen. Ein schönes Beispiel für einen entsprechenden Dialog habe ich unter http://www.peetersonline.nl/index.php/powershell/powershell-open-file-dialog-box/ gefunden.

Das dortige Skript nutzt den FileOpen-Dialog, d.h. die Datei muss vorhanden sein. Mit sehr wenig Aufwand lässt sich auch ein entsprechender Dialog zum Speichern basteln:

# Select-FileDialog Function  #
# Created by Hugo Peeters     #
# http://www.peetersonline.nl #
# modified by Uwe Ziegenhagen for SAVE #
###############################
# Note: store in your profile for easy use
# Example use:
# $file = Select-FileDialog -Title "Select a file" 
# -Directory "D:\scripts" -Filter "Powershell Scripts|(*.ps1)"
 
function Select-FileDialog
{
  param([string]$Title,[string]$Directory,[string]$Filter="All Files (*.*)|*.*")
     [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
# UZ: replaced OpenFileDialog by SaveFileDialog
$objForm = New-Object System.Windows.Forms.SaveFileDialog
$objForm.InitialDirectory = $Directory
$objForm.Filter = $Filter
$objForm.Title = $Title
$Show = $objForm.ShowDialog()
If ($Show -eq "OK"){
                Return $objForm.FileName
}
Else {
      Write-Error "Operation cancelled by user."
      }
}
$file = Select-FileDialog -Title "Select a file" -Directory "C:\" -Filter "All Files |(*.*)"
write-host $file

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website