Monday, June 8, 2015

#82 : Open File Dialog with Powershell

This is interesting that all GUI operations can be done with Powershell without any problem. Basically, most of the resources available to any .NET application applied to Powershell. This make Powershell more vast and limitless (in my opinion).

So, let's see the code which will be used to open a dialog. The requirement is simple, the script will show a dialog to open any file, if user has open a file then script will display file name or show if user has cancelled the dialog. I would suggest not to use this script for any scheduling or automated job as this will stuck your job till host reboot (I think).

#----------------------------------------------------------------------------------------#
#-- Function Declaration 
#----------------------------------------------------------------------------------------#

function Open-File([string] $initialDirectory ) 

{

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

    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.filter = "All files (*.*)| *.*"
    $OpenFileDialog.ShowDialog() |  Out-Null

    return $OpenFileDialog.filename
} 

#----------------------------------------------------------------------------------------#
#Usage : 
#----------------------------------------------------------------------------------------#

$File=Open-File "C:\temp\tips" 

if ( $File -ne "" ) 
{
    echo "You choose FileName: $File" 
} 
else 
{
    echo "No File was chosen"
}



 

No comments:

Post a Comment

#112: How to handle xml document in Powershell?

 In PowerShell, you can handle XML data using various cmdlets and methods provided by the .NET Framework. Here's a basic guide on how to...