Search code examples
powershellvariablesenvironment-variables

PowerShell - Merge two variables into one


I'm learning PowerShell so please forgive (what I'm sure is) a simple question.

I'm used to coding BATCH scripts and if I wanted to merge %USERDOMAIN% and %USERNAME% I would:

set zFullUsername=%USERDOMAIN%\%USERNAME%
echo %zFullUsername%

How can I do the same in PowerShell?

Thank you for your time.


Solution

  • In PowerShell, you can access environment variables in a few different ways. The way I recommend is to use the $env:VAR variable to access them.

    $user = $env:USERNAME
    $domain = $env:USERDOMAIN
    
    echo "$domain\$user"
    

    Note: \ is not an escape character in the PowerShell parser, ` is.

    Similarly to rendering the echo command (echo is an alias of Write-Output btw) you can create a username variable like so:

    $fullUserName = "$domain\$user"
    

    Or you can skip right to creating $fullUserName straight from the environment variables:

    $fullUserName = "${env:USERDOMAIN}\${env:USERNAME}"
    

    Note: When variables have non-alphanumeric characters in them, the ${} sequence tells PowerShell everything between the ${} is part of the variable name to expand.

    It seems the : in $env:VAR is actually an exception to this rule, as
    "Username: $env:USERNAME" does render correctly. So the ${} sequence above is optional.


    To avoid confusion when trying to apply this answer in other areas, if you needed to insert the value of an object property or some other expression within a string itself, you would use a sub-expression within the string instead, which is the $() sequence:

    $someVar = "Name: $($someObject.Name)"
    

    When using either ${} or $(), whitespace is not allowed to pad the outer {} or ().