locked
Powershell: Proper way to reference shared folder %username% RRS feed

  • Question

  • Hi All,

    Someone was very helpful in determining the proper code to edit a file:

    $File = 'c:\scripts\File.reg' $Content = Get-Content -Path $File | ForEach-Object { $_ -replace 'user',$ENV:USERNAME } Set-Content -Path $File -Value $Content

    I would like $File to reference \\server\%username%\File.reg. How do I make this happen?

    If I put that within quotes its literally looking for %username% instead of inserting username there.

    Monday, February 12, 2018 7:03 PM

Answers

  • PowerShell does not use %varname% syntax for environment variable substitution. PowerShell uses $Env:varname instead.

    There is a small "gotcha" because you want to embed the environment variable reference inside the string. Here are a couple of ways you can write this; one way:


    $File = "\\server\$($Env:USERNAME)\File.reg"

    another way:


    $File = "\\server\{0}\File.reg" -f $Env:USERNAME


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by SilentCow Monday, February 12, 2018 7:22 PM
    Monday, February 12, 2018 7:09 PM

All replies

  • PowerShell does not use %varname% syntax for environment variable substitution. PowerShell uses $Env:varname instead.

    There is a small "gotcha" because you want to embed the environment variable reference inside the string. Here are a couple of ways you can write this; one way:


    $File = "\\server\$($Env:USERNAME)\File.reg"

    another way:


    $File = "\\server\{0}\File.reg" -f $Env:USERNAME


    -- Bill Stewart [Bill_Stewart]

    • Marked as answer by SilentCow Monday, February 12, 2018 7:22 PM
    Monday, February 12, 2018 7:09 PM
  • Thanks BILL!!!!! Learned something else today.
    Monday, February 12, 2018 7:22 PM