Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string of text in powershell

Tags:

powershell

I'm trying to replace string of text and I get The regular expression pattern is not valid.

This is to be able to change a policy using LGPO

$TextToBeReplaced="Computer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nDeployConfigCIPolicy`r`nDWORD:1`r`n`r`nComputer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nConfigCIPolicyFilePath`r`nSZ:C:\\WL\\politicas\\DeviceGuardPolicy.bin"

$NewText="Computer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nDeployConfigCIPolicy`r`nDELETE`r`n`r`nComputer`r`nSOFTWARE\Policies\Microsoft\Windows\DeviceGuard`r`nConfigCIPolicyFilePath`r`nDELETE"

((Get-Content -path $LGPOTxt -Raw) -replace $TextToBeReplaced,$NewText) | Set-Content -Path $LGPOTxt

LGPO.txt contains this what I have to change is this string for the other in order to apply the new LGPO policy

; ----------------------------------------------------------------------
; PARSING Computer POLICY
; Source file:  C:\WL\LGPO\LGPOBackUp\DomainSysvol\GPO\Machine\registry.pol

Computer
SOFTWARE\Policies\Microsoft\Windows\DeviceGuard
DeployConfigCIPolicy
DWORD:1

Computer
SOFTWARE\Policies\Microsoft\Windows\DeviceGuard
ConfigCIPolicyFilePath
SZ:C:\\WL\\politicas\\DeviceGuardPolicy.bin

; PARSING COMPLETED.
; ----------------------------------------------------------------------

Any way to do this?

like image 760
marcosagni98 Avatar asked Dec 18 '25 16:12

marcosagni98


1 Answers

This is because -replace operator treats replacement text as regular expression.

<input> -replace <regular-expression>, <substitute>

Instead, you could use replace method on the string object.

(Get-Content -path $LGPOTxt -Raw).replace($TextToBeReplaced, $NewText) | Set-Content -Path $LGPOTxt
like image 95
Abdul Niyas P M Avatar answered Dec 21 '25 10:12

Abdul Niyas P M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!