首页 > 解决方案 > 如何用PowerShell中另一个变量的值替换字符串

问题描述

我正在尝试通过执行以下操作来修改系统路径环境变量。不幸的是,我观察到的是,如果我硬编码它可以工作的字符串,但我使用了一个变量(这是我更愿意做的),它就不起作用。

我没有错误;它只是行不通。这是我的代码:

$GlobalEnvPath = "C:\Path\ToApp\"
$CurrentEnvPath = [System.Environment]::GetEnvironmentVariable('PATH','Machine')
If ($CurrentEnvPath –match ".+?\;$") { $CurrentEnvPath = $CurrentEnvPath –replace ".{1}$" } #Sanitize the acquired string to remove any trailing semi-colons
$TempNewEnvPath = $CurrentEnvPath.Replace("$GlobalEnvPath",$null) #Find and replace the installation directory with a null value
$NewEnvPath = $TempNewEnvPath.Replace(";;",$null) #Find and replace any double semi-colons that may be present
[System.Environment]::SetEnvironmentVariable('PATH',$NewEnvPath,'Machine') #Finally, let’s write our changes back to the system registry

我遇到问题的部分是:

$TempNewEnvPath = $CurrentEnvPath.Replace("$GlobalEnvPath",$null)

任何帮助将不胜感激,谢谢。

标签: windowspowershell

解决方案


这是我建议的解决方案:

$path = @([Environment]::GetEnvironmentVariable('PATH', 'Machine') -split ';')

$exclude = [regex]::Escape('C:\Path\ToApp\' -replace '\\$')
$newPath = $path -notmatch $exclude -join ';'

[Environment]::SetEnvironmentVariable('PATH', $newPath, 'Machine')

这消除了很大的错误空间。 String#Replace例如,区分大小写。对于可能的边缘情况,我也没有使用尾部斜杠。


推荐阅读