Skip to content

Instantly share code, notes, and snippets.

@KevinMarquette
Created July 4, 2016 15:20
Show Gist options
  • Save KevinMarquette/ca06deb1320de0b49fdc732c68b9cfc8 to your computer and use it in GitHub Desktop.
Save KevinMarquette/ca06deb1320de0b49fdc732c68b9cfc8 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Used to replace text in a file.
.EXAMPLE
Get-ChildItem -Recurse | Set-String -Pattern "c:\documents" -ReplaceWith "c:\users"
.EXAMPLE
Set-String -Pattern "c:\documents" -ReplaceWith "c:\users" -Path c:\temp\script.ps1
#>
Function Set-String
{
[CmdLetBinding()]
param(
[Parameter(
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[Alias("fullname")]
[string[]]$Path,
[Parameter(
Mandatory = $true,
HelpMessage = "The pattern to be replaced",
Position = 1,
ValueFromPipelineByPropertyName = $true
)]
[string]$Pattern,
[Parameter(
Mandatory = $true,
HelpMessage = "The replacment text",
Position = 2,
ValueFromPipelineByPropertyName = $true
)]
[string]$ReplaceWith
)
process
{
$Speed = Measure-Command {
foreach($currentFile in (resolve-path $Path))
{
$Encoding = Get-FileEncoding $currentFile
Write-Verbose "Checking $CurrentFile"
(Get-Content $currentFile -raw) -replace $Pattern, $ReplaceWith |
Set-Content $currentFile -Encoding $Encoding
}
}
Write-Verbose "Processed in $($Speed.Seconds) Seconds"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment