Replace a string in a file with PowerShell

I have wanted to expand my PowerShell skills for some time, however I find it a steep learning curve. One thing I am learning is the result is worth it.

I recently needed to replace a string in a file. I searched a found the working parts I needed create this. I just wanted to post it here so I know where to come back and find it.

 

[CmdletBinding()]

param

(

    [Parameter(Mandatory=$True)]

    [string]$OldValue,

    [Parameter(Mandatory=$True)]

    [string]$NewValue,

    [Parameter(Mandatory=$True)]

    [string]$FilePath

)

(Get-Content $FilePath) |

Foreach-Object {$_ -replace "$OldValue","$NewValue"|

set-content $FilePath

 

A wonderful addition to this is you can even pop regular expressions into the $OldValue.

 

(Get-Content MySSAS.deploymenttargets) |

Foreach-Object {$_ -replace "<Server>(.*?)</Server>","<Server>__TargetDataBase__</Server>"}  |

set-content MySSAS.deploymenttargets