Skip to content

Instantly share code, notes, and snippets.

@chrisbrownie
Created September 20, 2016 23:07
Show Gist options
  • Save chrisbrownie/dccdd150e683718d682a0bbbb7e93952 to your computer and use it in GitHub Desktop.
Save chrisbrownie/dccdd150e683718d682a0bbbb7e93952 to your computer and use it in GitHub Desktop.
Adds or updates text between two markers in a text file.
function AddOrUpdateTextInFile() {
Param(
$File,
[string]$StartString,
[string]$EndString,
[string]$ReplacementString
)
$fileContent = Get-Content $File -ReadCount 512
if ($fileContent -match [System.Text.RegularExpressions.Regex]::Escape($StartString)) {
$numberOflines = $fileContent.Length
$FoundString = $false
$startLineNumber = $null
$endLineNumber = $null
for ($i=0; $i -lt $numberOflines; $i++) {
if (-not ($startLineNumber) -and ($fileContent[$i].ToString().Trim() -eq $StartString)) {
$startLineNumber = $i
} elseif (-not ($endLineNumber) -and ($fileContent[$i].ToString().Trim() -eq $EndString)) {
$endLineNumber = $i
}
}
$FileStartPart = $fileContent[0..($startLineNumber-1)]
$FileEndPart = $fileContent[($endLineNumber+1)..$numberOflines]
$NewContent = ($FileStartPart + $ReplacementString + $FileEndPart) -join "`r`n"
$NewContent | Out-File $File -Encoding ascii
} else {
# Could not find the start string, append to the end
Add-Content -Path $File -Value "`r`n" -Encoding ascii
Add-Content -Path $file -Value $ReplacementString -Encoding ascii
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment