Link to home
Start Free TrialLog in
Avatar of electricd7
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:

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  
    }  
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Qlemo
Qlemo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of electricd7
electricd7

ASKER

Looks like that would work, but what happens if $LogFile gets very large (which is possible in this app)?  Wouldn't this get problematic using Get-Content to pull the entire file into memory each and everytime the function is called?
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.