windows - 如何用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)
任何帮助将不胜感激,谢谢。
解决方案
这是我建议的解决方案:
$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
例如,区分大小写。对于可能的边缘情况,我也没有使用尾部斜杠。
推荐阅读
- php - 如何基于 UA 字符串检测基于 Chromium 的浏览器
- c++ - 隐式从 double 转换为 int 时没有精度损失警告
- algorithm - 根据活动、总里程和总时间标准化锻炼
- python - 将用户输入转换为布尔值并在 Python 中引发错误?
- sql - 如何在更新查询中使用 string_split?
- python - 将部分训练的 scikit-learn 模型存储或检查点到磁盘
- c# - 如何修复 System.InvalidOperationException 错误?
- javascript - 画布如何随窗口调整大小?
- python - 提交表单时页面未重定向
- wordpress - 帖子未根据元键值排序