I need to add a fixed string to the beginning of a text file. Then I need to add one to the end of the same text file.
Add-Content "MyString_beginning" -Value (Get-Content "C:\myexistingfile.txt")
Add-Content "P:\scripts\MPC.txt" "MyString_ending"
are these two commands how that is best done?
using
("- MPC**") (Get-Content -Path "P:\scripts\MPC.txt") "- **" |
>> Set-Content -Path "P:\scripts\MPC.txt"
I have my file with has lines 1-10 on it - when I try the memory permitting example it collapses all my existing rows WHY >?
CodePudding user response:
You could do (memory permitting)
(@("MyString_beginning") (Get-Content -Path "C:\myexistingfile.txt") "MyString_ending") -join [environment]::NewLine |
Set-Content -Path "C:\myexistingfile.txt"
Or something like
$template = @'
MyString_beginning
{0}
MyString_ending
'@
$template -f (Get-Content -Path "C:\myexistingfile.txt" -Raw) |
Set-Content -Path "C:\myexistingfile.txt"
If the file is very large, you could use a StreamReader to read the lines of the existing file and a StreamWriter to write to a temporary file. After this, you can delete the original file and move the temporary one to the original location.
$originalFile = "C:\myexistingfile.txt"
$tempfile = [System.IO.Path]::GetTempFileName()
# create a Reader and Writer object for the above paths
$reader = [System.IO.StreamReader]::new($originalFile)
$writer = [System.IO.StreamWriter]::new($tempfile)
# write your new top line
$writer.WriteLine("MyString_beginning")
while($null -ne ($line = $reader.ReadLine())) {
$writer.WriteLine($line)
}
# write your new bottom line
$writer.WriteLine("MyString_ending")
$writer.Flush()
$reader.Dispose()
$writer.Dispose()
# finally delete the original file and move the temp file
Remove-Item -Path $originalFile
Move-Item -Path $tempfile -Destination $originalFile