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:
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:
In PowerShell, you enter:
Or the long form of:
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!
Follow me on twitter: @EssentialExch