尝试从批处理脚本执行 运行 Powershell 命令时,PowerShell 用文本文件中的另一行替换行无法按预期工作

PowerShell replace line with another line in text file doesn't work as expected when attemtping to run Powershell commands from Batch script

正如我在标题中提到的,我创建了一个批处理脚本,它触发一些 Powershell 命令来替换 .ovpn 配置文件中的一行,该文件基本上是文本文件,包含所需的行,但它没有按预期工作。

这是.ovpn文件的当前内容,我正在尝试修改:

.....
.....
auth-user-pass "C:\path\to\.old-auth"
....
....

想要的文件内容是这样的:

.....
.....
auth-user-pass "C:\path\up\to\.new-auth"
....
....

为此,我编写了这个脚本,它应该可以毫无问题地更改确切的行,但显然这没有发生。在确保批处理脚本中的每个变量和字符串操作都正常工作之后,我不知道 Powershell 端出了什么问题:

@echo off && setlocal EnableDelayedExpansion

set "VpnCfgDir=C:\path\up\to\"
set "DestFile=!VpnCfgDir!\.new-auth"
set "VpnAuth=!DestFile!" && set "VpnAuth=!VpnAuth:\=\!"

PowerShell -ExecutionPolicy AllSigned -NoExit -NoLogo -NonInteractive -NoProfile -WindowStyle Maximized -Command "$line = Get-Content \"!VpnCfgDir!\<vpn_name>.ovpn\" | Select-String 'auth-user-pass' | Select-Object -ExpandProperty Line; $content = Get-Content \"!VpnCfgDir!\<vpn_name>.ovpn\"; $content = $content | ForEach-Object {$_ -replace $line, 'auth-user-pass \"%VpnAuth%\"'} | Set-Content \"!VpnCfgDir!\<vpn_name>.ovpn\""

任何人都可以帮助修复和实现预期的功能吗?

我认为这样的方法可行。在不知道您 运行 遇到的确切错误或问题的情况下,很难说,但我认为使用拆分对文本文件进行简单解析可能会奏效。

$contentPath  = \"!VpnCfgDir!\<vpn_name>.ovpn\"; Set-Content -Path $contentPath -Value ((Get-Content $contentPath | Select-String \"auth-user-pass\").ToString().Split(\".\")[0] + \".NewAuthHere\")

更易于阅读的格式:

$contentPath  = \"!VpnCfgDir!\<vpn_name>.ovpn\"
Set-Content -Path $contentPath -Value ((Get-Content $contentPath | 
Select-String \"auth-user-pass\").ToString().Split(\".\")[0] + \".NewAuthHere\")

我们还可以使用变量

使您的 .new-auth 文件名动态化
$newAuthFile = \".new-auth\";$contentPath  = \"!VpnCfgDir!\<vpn_name>.ovpn\";Set-Content $contentPath -Value ((Get-Content $contentPath | Select-String \"auth-user-pass\").ToString().Split(\".\")[0] + $newAuthFile)

更易于阅读的格式:

$newAuthFile = \".new-auth\"
$contentPath  = \"!VpnCfgDir!\<vpn_name>.ovpn\"
Set-Content $contentPath -Value ((Get-Content $contentPath | Select-String \"auth-user-pass\").ToString().Split(\".\")[0] + $newAuthFile)