PowerShell - 将两个变量合二为一 [英] PowerShell - Merge two variables into one

查看:50
本文介绍了PowerShell - 将两个变量合二为一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

set zFullUsername=%USERDOMAIN%\%USERNAME%回声 %zFullUsername%

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

感谢您抽出宝贵时间.

解决方案

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

$user = $env:USERNAME$domain = $env:USERDOMAINecho "$domain\$user";

<块引用>

注意:\ 不是 PowerShell 解析器中的转义字符,` 是.

类似于渲染 echo 命令(echoWrite-Output 顺便说一句的别名),您可以创建一个用户名变量,如下所示:

$fullUserName = "$domain\$user";

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

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

<块引用>

注意:当变量中包含非字母数字字符时,${} 序列告诉 PowerShell ${} 之间的所有内容都是要扩展的变量名称的一部分.

看来 $env:VAR 中的 : 实际上是此规则的一个例外,如
Username: $env:USERNAME"; 确实渲染正确.所以上面的 ${} 序列是可选的.


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

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

<块引用>

当使用 ${}$() 时,不允许用空格填充外部 {}().

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.

解决方案

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 ().

这篇关于PowerShell - 将两个变量合二为一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆