PowerShell: Playing with Environment Variables

Enivornment Variables make life easier. In this article I describe how to use environment variables in daily work. And I am going to show some useful examples.

Finding Environment Variables

In cmd, all varialbes can be shown by using the command set.


Surprisingly, that does not work in PowerShell:


In PowerShell set refers to Set-Variable. So we have to take another path.


In PowerShell, all environment variables are stored in the PowerShell Drive env.


To list all of them run

Get-ChildItem -Path env:


cd env:


Why Environment Variables?

Imagine you have to copy a folder from one system to another system. The folder should be stored in the root directory of Windows. With environment variables you do not have to care of the location of the Windows directory. The installation of Windows in C:\Windows is not mandatory. Just use the variable windir, and it should use the correct folder.

Copy-Item -Path C:\Temp\computers.txt -Destination $env:windir


Cool stuff. Environment Variables can also help you to switch to a directory in a faster way.



Finding out the Computer Name


Ok, I have to admit: It´s easier to use the command hostname. 😉


Finding out the Logonserver



Configure a Scheduled Task

For example, if you want to start PowerShell at every logon run this code and pay attention to line 4. There you see the username environment variable in action.

$Action=New-ScheduledTaskAction -Execute "powershell.exe"
$Trigger=New-ScheduledTaskTrigger -AtLogOn
$Principal=New-ScheduledTaskPrincipal -UserID "$env:username" -LogonType Interactive -RunLevel Highest
$Task=New-ScheduledTask -Action $Action -Trigger $Trigger -Settings $Set -Principal $Principal
Register-ScheduledTask -TaskName PowerShellAtLogon -InputObject $Task



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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.