Hi,
Before working on script i always thought that these windows “Environment Variables” are not so important, but as i start working on PowerShell and start working on script i realise that these windows “Environment Variables” are very useful. I uses these windows “Environment Variables” in most of my scripts.
Why these windows “Environment Variables” are important?
For example you are using a script which create a SYSTEM REPORT which contain username, computer name, and Logon server, so where you will find these details ? exactly in windows “Environment Variables. In another example , i am have a script which sent an email to "someone" but it also send a BCC email to sender, so how to access sender email ID ? i know that in windows “Environment Variables doesn't contain the any email-id, but we can create it using some trick using windows “Environment Variables.
Enough theory, Lets Start!!
How to access all windows “Environment Variables.?
In PowerShell accessing of windows “Environment Variables is very simple. the windows “Environment Variables are mounted as PsDrive in PowerShell. You just need to do run DIR on Env:\, like this "Dir env:\" .
And this will show you all “Environment Variables which you have on your system.
How to access the value of “Environment Variables" using PowerShell?.
Actually there are many ways to access the values of windows "Environment Variables", i mostly used two ways to access these values and the result is same in both ways.
using Get-Item
We can use Get-Item to get the value of desired "Environment Variable". Run the below command.
Get-Item env:\USERNAME
In the output it showing the us the value of USERNAME environment variable but along with value it also showing the "Name" in output. Let omit it.
(Get-Item env:\USERNAME).value
Enclose the whole command in bracket after closing the bracket we are choosing to show .value properties. and you can seen below it showing us only the value of USERNAME environment variable .
Using $ENV:
Actually this is the easy method to access the value of windows environment variables. just use $Env: and after colon provide the environment variable whose value you want to see.
$Env:username
Simple :) isn't.
Usage {at least for me}
Example 1:
I construct email id using Username environment variable. I know in my "Foo" company every one is having there username@foo.net email id. so i construct email id like this
$email = $env:username + '@foo.net'
Example 2:
In some of my script i used this trick, So that i know which user is logged on which laptop and at what time.
Write-host "The user `"$env:username`" logged in to laptop `"$env:computername`" on $(Get-Date)" -ForegroundColor Yellow
Video
Thanks for reading ..
Aman Dhally
