0

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?

zdan
  • 28,667
  • 7
  • 60
  • 71
forjahead
  • 3
  • 1
  • The one combination you *didn’t* try is ```$($env:UserDomain)``` :-). – mclayton May 17 '23 at 22:13
  • Your second option works: `"c:\Users\$env:UserDomain"+"_"+"$env:UserName"`. Without seeing the error we won't be able to tell you why it wasn't working for you. – jerdub1993 May 18 '23 at 05:50

1 Answers1

1

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"
mklement0
  • 382,024
  • 64
  • 607
  • 775