In PowerShell, how can I convert environment variables (like $SystemRoot$) if they are part of a string?
environment-variables, powershell, regex, registry, windows
Solution
Using .net. Try this:
[System.Environment]::ExpandEnvironmentVariables("%SystemRoot%\System32\Winevt\Logs\DebugChannel.etl")
Problem
I'm trying to write a script which reads file paths from a set of registry keys, but these paths have environment variables like %SystemRoot% in. I know you can usually look up the value of these using: ``` $env:SystemRoot ``` for example. However, if PS receives a string such as "%SystemRoot%\System32\Winevt\Logs\DebugChannel.etl", how can this get converted to the full path I need, i.e. "C:\Windows\System32\Winevt\Logs\DebugChannel.etl"? I've tried using a regex -replace to convert the %% format to the $env: format: ``` $_.FileName -replace "%(\w*)%\\", "`$env:`${1}\" ``` But this just results in the string: ``` $env:SystemRoot\System32\Winevt\Logs\DebugChannel.etl ``` And I'm not sure how to get PowerShell to actually evaluate the "$env:SystemRoot" part. I presume there is a more sensible way of doing this anyway! The full code I'm using to get the registry values and produce the above result is ``` Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Control\WMI\Autologger | Get-ItemProperty -Name "FileName" -ErrorAction SilentlyContinue | foreach { if($_.FileName) { $_.FileName -replace "%(\w*)%\\", "`$env:`${1}\" } } ``` Thanks.