1

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.

englealuze
  • 1,445
  • 12
  • 19
  • 1
    In PowerShell you can access environment variables via a 'drive' just like it's any other drive. From a console try using Set-Location env: and then issue a dir (just like you would for your C: drive). You can switch back to C: by typing Set-Location C:. These Environment drive objects can also be accessed (and echo'd out) by typing $env:variablename, for example $env:userprofile. – nimizen Jun 24 '22 at 09:09
  • This is a type of 'drive' is called a PSDrive, you can search online for PSDrive to find out more. – nimizen Jun 24 '22 at 09:17

1 Answers1

1

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

NiMux
  • 826
  • 7
  • 16