英文:
Use environment variables to identify a directory in Powershell
问题
In a Powershell script, you can create a directory using the domain and user name from environment variables like this:
New-Item -Path "c:\Users\$($env:UserDomain)_$($env:UserName)" -ItemType Directory
This command will create a directory in the format "c:\Users\FOOBAR_kilroy" based on the values of the "UserDomain" and "UserName" environment variables.
英文:
New to Powershell.
In a Powershell script, I'm trying to create a directory using the domain and user name as pulled from environment variables. So for domain\user "FOOBAR\kilroy" I want to create something like c:\Users\FOOBAR_kilroy.
I've tried
"c:\Users$(env:UserDomain)"+"_"+"$(env:UserName)";
"c:\Users$env:UserDomain"+"_"+"$env:UserName"; and
"c:\Users\env:UserDomain_$(env:UserName)".
All the above generate an error.
What am I missing?
答案1
得分: 1
在一个可展开的(双引号)字符串("..."
)中:
-
您可以嵌入甚至是_带有命名空间限定_的变量引用,例如
$env:USERDOMAIN
原样。 -
但是,与任何嵌入的变量引用一样,将(可能带有命名空间限定的)名称封装在
{...}
中(例如${env:USERDOMAIN}
)可能是必要的,以区分变量名称与_后续字符_,例如您的情况下的_
,因为_
是 PowerShell 变量名称的一部分_不需要_用{...}
封装。
因此:
"c:\Users${env:USERDOMAIN}_$env:USERNAME"
英文:
In an expandable (double-quoted) string ("..."
):
-
You can embed even namespace-qualified variable references such as
$env:USERDOMAIN
as-is.- Enclosure in
$(...)
, the subexpression operator is only needed for expressions and commands, such as$($env:USERDOMAIN.Length)
,$($args[0])
,$(1 + 2)
, or$(Get-Date)
- see this answer for a comprehensive overview of PowerShell's string interpolation.
- Enclosure in
-
However, as with any embedded variable reference, enclosure of the (potentially namespace-qualified) name in
{...}
(e.g.${env:USERDOMAIN}
) may be necessary in order to disambiguate variable names from subsequent characters, such as_
in your case, given that_
is a character that can be part of a PowerShell variable name without enclosure in{...}
.
Therefore:
"c:\Users${env:USERDOMAIN}_$env:USERNAME"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论