PowerTip: Expand Environmental Variables with PowerShell


Summary: Learn to expand the value of environmental variables by using Windows PowerShell.

Hey, Scripting Guy! Question How can I use Windows PowerShell to find the value of a common environmental variable
           such as %username% or %computername%?

Hey, Scripting Guy! Answer Use the ExpandEnvornmentalVariables static method from the
           System.Environment .NET Framework class, for example:

[System.Environment]::ExpandEnvironmentVariables("%username%")

[System.Environment]::ExpandEnvironmentVariables("%computername%")

Comments (8)

  1. Anonymous says:

    The built-in version doesn’t seem to be more complicated than the .NET – version

    PS H:> "This is my $env:computername and it is ver fast for me: $env:username"
    This is my KCN4133 and it is ver fast for me: kc4gia

    In PS there are often different solutions for the same "problem"!

  2. Anonymous says:

    How about the more simple:
    $env:username
    or if you want to see all environment variables
    Get-ChildItem env:

  3. Chen V says:

    This is also faster
    "This is {0} my computer name" -f [System.Environment]::GetEnvironmentVariable(‘COMPUTERNAME’)

  4. jrv says:

    But that is nost all.

    PS C:scripts> [System.Environment]::ExpandEnvironmentVariables("This is my %computername% and it is very fast for me: %
    username%")
    This is my W8TEST and it is very fast for me: jsmith
    PS C:scripts>

  5. Jacob says:

    So, it’s very nice that PowerShell can interact with .NET classes, but wouldn’t it be better to use the built-in support for environment variables?

    PS C:> Write-Output $env:COMPUTERNAME
    JACOB-WINDOWS8

    PS C:> Get-Item Env:COMPUTERNAME

    Name Value
    —- —–
    COMPUTERNAME JACOB-WINDOWS8

    For more information about the Env: "drive" (provider), see the PowerShell documentation, such as "help about_Providers".

  6. (Jessica Ramos;)/[*.] window.com says:

    LCAP

  7. (*Jessica Ramos;) says:

    (*Jessica Ramos;)[Browser.Enviorment]::WindowEnviornment("%HPDeskTop%")Chrome-Window-Browser

  8. Max says:

    this does not work in windows 2012 for me

    in powershell I run

    [Environment]::SetEnvironmentVariable("MYVAR", "c:temp", "Machine")
    [Environment]::SetEnvironmentVariable("MYVAR2", "%MYVAR%", "Machine")

    then I run sysdm.cpl from task manager

    I see my variables BUT
    MYVAR2 appears as %MYVAR%
    and does not expand!!

    researching this for hours now all the articles only talk about expanding env vars but not setting them properly.
    the registry method also doesn’t work (same result).

    HELP!!!

Skip to main content