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: , ,
© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: