#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.
Share on: