Browse for File to POSH Variable

After many months of getting tired of typing in an entire directory path when using the “Read-Host” command to import a text file or CSV file I went looking for commands to present a popup box to let me browse for a file, then have that file’s path be presented to a variable. This example shows that $file will be the file path for the file specified in the Get-FileName function.

A big thank you goes to the blog over at Sapien.com for showing me this wonderfulness ūüôā

http://www.sapien.com/forums/scriptinganswers/forum_posts.asp?TID=4115


Function Get-FileName($initialDirectory)

{

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

Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog

$OpenFileDialog.initialDirectory = $initialDirectory

$OpenFileDialog.Title = "PowerShell Master Says...Select File:"

$OpenFileDialog.filter = "All files (*.*)| *.*"

$OpenFileDialog.ShowDialog() | Out-Null

$OpenFileDialog.filename

} #end function Get-FileName

# *** Entry Point to Script ***

$file = Get-FileName -initialDirectory "c:"

Posted in PowerShell and tagged , , , , , , , , , , , , , , .

2 Comments

  1. Im glad I could provide some help to the community. I feel that its only right to give back when I use the community for my own research. If you ever need help or have questions feel free to hit me up

Leave a Reply

Your email address will not be published. Required fields are marked *