Last active
April 5, 2020 11:37
-
-
Save tjgruber/682e3956c34465290d6706277d317b9f to your computer and use it in GitHub Desktop.
Replace-LineInText PowerShell function to replace a specific line in a file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Replace-LineInText { | |
[CmdletBinding()] | |
param ( | |
[Parameter(Position=0)] | |
[string]$fileDirectory, | |
[Parameter(Position=1)] | |
[string]$fileExtension, | |
[Parameter(Position=2)] | |
[int]$lineNumber, | |
[Parameter(Position=3)] | |
[string]$replacementText | |
) | |
Write-Output "fileDirectory set to [$fileDirectory]" | |
Write-Output "fileExtension set to [$fileExtension]" | |
Write-Output "lineNumber set to [$lineNumber]" | |
Write-Output "replacementText set to [$replacementText]" | |
$files = Get-ChildItem -Path $fileDirectory -Filter "*$fileExtension" | |
[int]$pLineNumber = $lineNumber-1 | |
foreach ($file in $files) { | |
Write-Output "Processing [$($file.FullName)]..." | |
$fileContentFirstHalf = Get-Content $file.FullName | Select-Object -First $pLineNumber | |
$fileContentSecondHalf = Get-Content $file.FullName | Select-Object -Skip $lineNumber | |
$newContent = $fileContentFirstHalf+$replacementText+$fileContentSecondHalf | |
Set-Content -Path $file.FullName -Value $newContent -Force | |
Write-Output "`tLine [$lineNumber] has been set to [$(Get-Content $file.FullName | Select-Object -Skip $pLineNumber -First 1)]" | |
} | |
} | |
# Run the function | |
Replace-LineInText ` | |
-fileDirectory "C:\files\directory" ` | |
-fileExtension ".txt" ` | |
-lineNumber 23 ` | |
-replacementText "This is the replacement text" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment