Home > PowerShell > Browse for File to POSH Variable

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 = <strong>New-Object</strong> 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 <em>-initialDirectory</em> "c:\"


Advertisements
  1. September 1, 2013 at 2:59 am

    We are a gaggle of volunteers and starting a new scheme in our community.
    Your site offered us with useful info to work on.
    You’ve done an impressive task and our whole community shall be thankful to you.

    • September 1, 2013 at 3:10 am

      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

  2. September 26, 2013 at 1:54 am

    Howdy! I’m at work surfing around your blog
    from my new iphone 4! Just wanted to say I love reading your blog and
    look forward to all your posts! Carry on the outstanding work!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: