我正在尝试编写一个脚本,该脚本从一组注册表项中读取文件路径,但这些路径具有 %SystemRoot% 之类的环境变量。我知道您通常可以使用以下方法查找这些路径的值:
$env:SystemRoot
例如。但是,如果 PS 收到一个字符串,如“%SystemRoot%\System32\Winevt\Logs\DebugChannel.etl”,如何将其转换为我需要的完整路径,即“C:\Windows\System32\Winevt\Logs\DebugChannel.etl"?
我试过使用 regex -replace 将 %% 格式转换为 $env: 格式:
$_.FileName -replace "%(\w*)%\\", "`$env:`${1}\"
但这只会导致字符串:
$env:SystemRoot\System32\Winevt\Logs\DebugChannel.etl
而且我不确定如何让 PowerShell 实际评估“$env:SystemRoot”部分。无论如何,我认为有一种更明智的方法可以做到这一点!
我用来获取注册表值并产生上述结果的完整代码是
Get-ChildItem HKLM:\SYSTEM\CurrentControlSet\Control\WMI\Autologger | Get-ItemProperty -Name "FileName" -ErrorAction SilentlyContinue | foreach { if($_.FileName) { $_.FileName -replace "%(\w*)%\\", "`$env:`${1}\" } }
谢谢。
最佳答案
使用.net。试试这个:
[System.Environment]::ExpandEnvironmentVariables("%SystemRoot%\System32\Winevt\Logs\DebugChannel.etl")
关于regex - 在 PowerShell 中,如果环境变量(如 $SystemRoot$)是字符串的一部分,我该如何转换它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20071045/