Logging with PowerShell

Hello,

As many of you may know, when you write a PowerShell script, you need to log all actions that performs modifications in order to keep tracks.Usually, I used the Add-Content cmdlet, that can appen data do a text file, prettu useful. The downside of that cmdlet is that it has some impact on performances, indeed, it writes to disk everytime you call it.

If you need your script to run faster, you can use a StreamWriter object :

$LogFile = "C:TempLog.log"
$LogFileStream = New-Object System.IO.StreamWriter $LogFile
$LogFileStream.WriteLine($(Get-Date))
$LogFileStream.WriteLine("")#White line
$LogFileStream.Close()

You only need to create the object ones, use it, and then at the end of the script, you close it.

Leave a Reply