2

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?

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

7 Comments

it doesnt changed it I applied just like you did
it seems is not working because is in several lines, but i want to keep that text structure
Can you update the question with sample $LGPOTxt file content?
I updated, adding the content of the txt
Nice, though it's worth noting that the [string] type's .Replace() method is case-sensitive, unlike PowerShell's -replace operator. In Windows PowerShell, this cannot be helped; in PowerShell (Core) 7+, there is a new overload that allows case-insensitivity as an opt-in.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.