Home > Software engineering >  echo/access environmental variables from powershell
echo/access environmental variables from powershell

Time:06-25

In windows cmd I could echo any environmental variable with echo %VARIABLENAME%, such as

enter image description here

But in powershell, this behavior is inconsistent and I could not understand. For certain variables like $HOME I could do the same thing (echo $VARIABLENAME) as in windows cmd.

enter image description here

But for some other variables I could not simply echo but have to use .NET's class methods, such like

enter image description here

I would like to:

  1. Understand the difference between Powershell and windows cmd. Why they behave differently when accessing and printing environmental variables.
  2. Understand why certain variable is echolable while others are not in powershell. What is the rule behind that.

I am new to powershell. The purpose of this question is not just getting the variable printed, but understanding how things work in powershell and the difference between windows cmd, so that I could better use it.

CodePudding user response:

PowerShell exposes environmental variables via the $Env: scope (you can read more about scopes here)

So to access the USERPROFILE environmental variable, you could do the following (note, I'm using Write-Host in place of echo here, see this answer for details on the difference between the two):

Write-Host $Env:USERPROFILE

PowerShell also exposes a number of automatic variables and these are made available to all scripts and commands. $HOME for example is one such automatic variable.

For further information on these, see Automatic Variables

  • Related