Different ways to perform string manipulation within a file in PowerShell.

Replace text

Powershell version 3 and above

(Get-Content c:\temp\test.txt).replace('[MYID]', 'MyValue') | Set-Content c:\temp\test.txt

Powershell version 2

(Get-Content c:\temp\test.txt) -replace '\[MYID\]', 'MyValue' | Set-Content c:\temp\test.txt

In version 2 \ sign need to be present before a spiecial character.

Remove blank spaces

(Get-Content c:\temp\test.txt) -notmatch '(^[\s,-]*$)|(rows\s*affected)' | Set-Content c:\temp\test.txt

Categorized in:

Powershell,

Last Update: May 18, 2024