PowerShell - 将两个变量合并为一个

PowerShell - Merge two variables into one

我正在学习 PowerShell,所以请原谅(我确定是)一个简单的问题。

我习惯于编写 BATCH 脚本,如果我想合并 %USERDOMAIN% 和 %USERNAME%,我会:

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

如何在 PowerShell 中执行相同的操作?

感谢您的宝贵时间。

在 PowerShell 中,您可以通过几种不同的方式访问环境变量。我推荐的方法是使用 $env:VAR 变量来访问它们。

$user = $env:USERNAME
$domain = $env:USERDOMAIN

echo "$domain$user"

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

类似于呈现 echo 命令(echoWrite-Output 顺便说一句的别名)你可以像这样创建一个用户名变量:

$fullUserName = "$domain$user"

或者您可以直接从环境变量中直接跳到创建 $fullUserName

$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.


如果您需要在字符串中插入对象 属性 或其他表达式的值,则在尝试将此答案应用于其他领域时避免混淆本身,您可以在字符串中使用子表达式,即 $() 序列:

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

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

在受支持的操作系统上,我什至不会为此烦恼环境变量:

$zFullUsername = whoami

然后按需访问即可:

$zFullUsername