Use environment variables to identify a directory in Powershell.

huangapple go评论60阅读模式
英文:

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.Length)$($args[0])$(1 + 2)$(Get-Date) - 详细了解 PowerShell 字符串内插的综合概述,请参阅此答案
  • 但是,与任何嵌入的变量引用一样,将(可能带有命名空间限定的)名称封装在 {...} 中(例如 ${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.
  • 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"

huangapple
  • 本文由 发表于 2023年5月18日 06:04:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76276480.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定