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:
or
cd env: dir
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.
Examples
Finding out the Computer Name
$env:computername
Ok, I have to admit: It´s easier to use the command hostname. 😉
Finding out the Logonserver
$env: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 $Set=New-ScheduledTaskSettingsSet $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
Categories: PowerShell, Windows 10, Windows Server