3

#PSTip How to expand environment variable contained in a text file

Let’s presume you have a text file that contains the following two lines:

My current user profile is $env:USERPROFILE.
The system folder is $env:windir\System32.

If you use the Get-Content cmdlet to output the content, the environment variables will not be expanded:

PS> Get-Content .\test.txt
My current user profile is $env:USERPROFILE.
The system folder is $env:windir\System32.

The solution is to use the ExpandString() method as in:

PS> Get-Content .\test.txt | ForEach-Object { $ExecutionContext.InvokeCommand.ExpandString($_) }
My current user profile is C:\Users\Aleksandar.
The system folder is C:\Windows\System32.
Filed in: Columns, Tips and Tricks Tags: , ,

3 Responses to "#PSTip How to expand environment variable contained in a text file"

  1. Josh Miller says:

    This will also remove double quotes as it will evaluate the content as a string. I changed:
    ($_)
    to
    (($_ -replace ‘”‘,’`”‘))
    to preserve quotes.

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: