N
N
nordz0r2021-11-06 18:54:00
PowerShell
nordz0r, 2021-11-06 18:54:00

How to change only the first found value in powershell?

Good evening, tell me how can I modify the code so that only the first match found is changed (and not everything after -match)

$VPNServer = "vpn.domain.ru"
$ConfigVPN = "$env:APPDATA\Microsoft\Network\Connections\Pbk\rasphone.pbk"
$output = (Get-Content ("$ConfigVPN") -Raw) -split '(?=\+\])' | 
foreach {
   if ($_ -match "$VPNServer"){
   $tmp = $_
   $tmp = $tmp -replace 'ExcludedProtocols=\d+','ExcludedProtocols=8'
   $tmp = $tmp -replace 'DisableClassBasedDefaultRoute=\d+','DisableClassBasedDefaultRoute=1'
   $tmp = $tmp -replace 'PreferredHwFlow=\d+','PreferredHwFlow=1'
   $tmp = $tmp -replace 'PreferredProtocol=\d+','PreferredProtocol=1'
   $tmp = $tmp -replace 'PreferredCompression=\d+','PreferredCompression=1'
   $tmp = $tmp -replace 'PreferredSpeaker=\d+','PreferredSpeaker=1'
   $tmp = $tmp -replace 'AutoTiggerCapable=\d+','AutoTiggerCapable=1'
   $tmp } else {$_}
}
$output = $output -join ''
$output

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MaxKozlov, 2021-11-07
@MaxKozlov

I think you should go the more general route.
since rasphone.pbk is actually an ini, you should look for something about reading ini files on powershell
, for example, this is a classic
https://devblogs.microsoft.com/scripting/use-power...

M
Morrowind, 2021-11-08
@hekkaaa

Hello.
If you want a solution in your own code, then you simply do not have enough breakin the if condition .
Here is a simple demo example:

$hostPC = ("ya.ru", , "ya.ru", "ya.ru", "google.ru","docs.microsoft.com")
foreach ($item in $hostPC) {
   if($item -eq "ya.ru"){
       Write-Host("MEOW");
       break;
   }
}

If it's not clear, run the code with and without break .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question