Ultra GC
Ultra GC

Reputation: 351

Using Powershell to locate and update key value in a text file

I have a text file (test.txt) containing the below:

User : MikeyMouse
Pswd : mycrazypswd
connectionstring : serverepor:80,pass=809hjhlkusfasdf,somepropert=somevalue

I need to use PS to update the above file's key value to mask passwords as shown below with "---"

sser : MikeyMouse
pswd : my---wd
connectionstring : serverepor:80,pass=80---df,somepropert=somevalue

Any suggestions on how bet to do that?

Thanks

Upvotes: 1

Views: 1148

Answers (1)

Sage Pourpre
Sage Pourpre

Reputation: 10323

Using Get/Set-Content and a Regex -Replace will do the trick.

$Path = 'test.txt'
$NewContent = (Get-Content -Path $Path -Raw) -replace '(?<=Pswd : ..)(.*)(?=..\r)', '---' -replace '(?<=pass=..)(.*?)(?=..,)', '---' 
Set-Content -Path $Path -Value $NewContent

References:

.Net Regex cheat sheet

Special thanks

@olaf: For showing me the lookahead/lookbehind way.

Upvotes: 2

Related Questions