PowerTip: Expand Environmental Variables with PowerShell

PowerTip: Expand Environmental Variables with PowerShell

  • Comments 6
  • Likes

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%")

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • 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".

  • 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>

  • 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"!

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

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