electricd7
asked on
How do I add content to the TOP of a text file from PowerShell?
Hello,
I have a simple log function written that takes a string as an argument ($Msg), prepends it with the current date/time (if $LogTime is passed) and adds it to the bottom of a given txt file. What I would like instead is a way to add the argument prepended with the date/time to the TOP of the given txt file. How would I go about doing this?? Here is my current function:
I have a simple log function written that takes a string as an argument ($Msg), prepends it with the current date/time (if $LogTime is passed) and adds it to the bottom of a given txt file. What I would like instead is a way to add the argument prepended with the date/time to the TOP of the given txt file. How would I go about doing this?? Here is my current function:
function Write-Log($Msg, [System.Boolean]$LogTime=$true){
if($LogTime){
$date = Get-Date -format dd.MM.yyyy
$time = Get-Date -format HH:mm:ss
Add-Content -Path $LogFile -Value ($date + " " + $time + " " + $Msg)
}
else{
Add-Content -Path $LogFile -Value $Msg
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Of course. But would it be wise to place the log entry at the top every 10 milliseconds? No. Logfiles use append for this reason (because it is an atomic, low-profile action). Tools are very effective in reading the tail of a text file for the same reason - optimized for that case.
Usually, if you want to have a reversed logging file, management is done different: The logfile is cut off at a certain size, moving out older entries. in that case the logging function is deterministic in its timing, and logfiles are fixed or almost fixed size.
Usually, if you want to have a reversed logging file, management is done different: The logfile is cut off at a certain size, moving out older entries. in that case the logging function is deterministic in its timing, and logfiles are fixed or almost fixed size.
ASKER