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:


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:

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!

Follow me on twitter: @EssentialExch

1 Reply to “Getting Our Computername in a PowerShell Script”

  1. Ten years later, in December of 2018, I would use $env:ComputerName.

    But this the equivalent of “gc env:ComputerName”.

    Perf-wise, it doesn’t make any difference.

Leave a Reply

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