PowerShell

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.

1.PNG

Surprisingly, that does not work in PowerShell:

2.PNG

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

Unbenannt.PNG

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

3.PNG

To list all of them run


Get-ChildItem -Path env:

or


cd env:
dir

5.PNG

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

5.PNG

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

5.PNG

Examples

Finding out the Computer Name


$env:computername

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

5.PNG

Finding out the Logonserver


$env:logonserver

5.PNG

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

Unbenannt.JPG

Unbenannt.PNG

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s