Home > Mobile >  PowerShell replace line with another line in text file doesn't work as expected when attemtping
PowerShell replace line with another line in text file doesn't work as expected when attemtping

Time:01-14

As I mentioned in title, I have created a Batch script which fires some Powershell commands for replacing a line in the .ovpn config file which is basically text file, with desired line, but it doesn't work as expected.

This is the current content of the .ovpn file, I am trying to modify:

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

And desired content of the file is this:

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

And for that I have writtent this script which is supposed to change the exact line without any issues, but clearly that's not happening. And after making sure that every variable and string manipulation in Batch script is working, I have no clue what's going wrong on Powershell's end:

@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\""

Can anyone help fixing and achieving the intended functionality ?

CodePudding user response:

I think something like this could work. Without knowing the exact error or issue you're running into, It's hard to say but I think a simple parse of the text file using a split could work.

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

Easier to read format:

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

We could also make your .new-auth file name dynamic using a variable

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

Easier to read format:

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