Getting Our Computername in a PowerShell Script

There are lots of reasons why you may want to get the name of your computer while you are executing a PowerShell script, from a parameter you want to pass to a cmdlet or function or for generating a filename.

Thankfully, PowerShell makes it easy.

Just like our old friend, cmd.exe, PowerShell makes the system-level environment variables available. Unlike cmd.exe, PowerShell doesn't make them available by surrounding the environment variable by a percentage symbols. Instead, PowerShell uses a provider. This provider makes Environment variables look like a file system and allows you to access (or set) their contents by reading (or writing) that content.

For example, to examine all environment variables and see their contents in cmd.exe, you enter:

set

To get the equivalent output in PowerShell (including the variables being sorted by name), you enter:

dir env: | sort Name

In cmd.exe, to display the value of COMPUTERNAME, you enter:

echo %COMPUTERNAME%

In PowerShell, you enter:

gc env:computername

Or the long form of:

get-content env:computername

And to store the value of the computername into a variable in PowerShell:

$computer = gc env:computername

We'll use this in my next post.

Until next time...

As always, if there are items you would like me to talk about, please drop me a line and let me know!

Published Tuesday, November 25, 2008 7:46 AM by michael
Filed under: ,

Comments

Thursday, December 11, 2008 3:30 PM by Michael's meanderings...

# Getting a List of Storagegroups in a PowerShell Script

In Getting Our Computername in a PowerShell Script , you learned how to do just that - store the running