Implementing logging (to log file) in Powershell Scripts

Many of the times one requires to setup logging for a script that is very huge in code and/or critical in it’s activities.  Here is a quick PS function code that I authored which simply logs all the log statements to a given file (for this example, I used C:tempTest.log file).

Code:

$LogFile    = ‘C:tempTest.log’
function MyLog {
    param ([string]$msg, [int]$flag)
    $date = get-date -format MM:dd:yyyy-HH:mm:ss
    Write-Output "msg received is [ $msg ] flag received is: [ $flag ]" | Out-File $LogFile -append
    if ($flag -eq 0) {
        Write-Output "$date INFO: $msg" | Out-File $LogFile -append
    } elseif ($flag -eq 1) {
        Write-Output "$date WARNING: $msg" | Out-File $LogFile -append
    } elseif ($flag -eq 2) {
        Write-Output "$date ERROR: $msg" | Out-File $LogFile -append
    } elseif ($flag -eq 3) {
        Write-Output "$date DEBUG: $msg" | Out-File $LogFile -append
    }
}

MyLog "Test0" 0
MyLog "Test1" 1
MyLog "Test2" 2
MyLog "Test3" 3

 

Output:

D:>type C:tempTest.log
05:24:2011-16:29:40 INFO: Message received is Test0
05:24:2011-16:29:40 WARNING: Message received is Test1
05:24:2011-16:29:40 ERROR: Message received is Test2
05:24:2011-16:29:40 DEBUG: Message received is Test3

D:>

0 thoughts on “Implementing logging (to log file) in Powershell Scripts

Leave a Reply

Your email address will not be published. Required fields are marked *