#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.

About the author: Aleksandar Nikolic

Aleksandar is a PowerShell MVP and a co-founder of PowerShell Magazine. He is a frequent speaker at the conferences and participates regularly in IT Pro user groups worldwide. Recently, Aleksandar co-authored the highly respected Administrator’s Guide to Windows PowerShell Remoting. Follow him on Twitter at @alexandair

Related Posts