Logger in Powershell

The below functions can be used as Logger and Exception Logger in power shell.

  • The Logger function can be used to log the message in a file
  • The Log_Exception function can be used to log the exception thrown at any try{} .. catch{} statements.
  • The Test_Exception function is a driver function 



 <#Read Me:
    Developed By:
                Name:Vaneeswaran N
                www.vaneeswaran.com
#>
$Function_Exit_Status = $false #Variable to store the exit status of the function

function Logger ($Log_Message , $Log_File)
{
    try 
        {   
        $log_str = "$(Get-Date -format "yyyy MMM d hh:mm:ss")           $Log_Message  "
        echo $log_str >> $Log_File
        }
   catch
        {
            write-host Caught an exception: -ForegroundColor Red
            write-host Exception Type: $($_.Exception.GetType().FullName) -ForegroundColor Red
            write-host Exception Message: $($_.Exception.Message) -ForegroundColor Red      
        }
}
   
function Log_Exception($type,$Log_Message)
{
    write-host Caught an exception:  -ForegroundColor Red
    write-host Exception Type: $type  -ForegroundColor Red
    write-host Exception Message: $Log_Message  -ForegroundColor Red
    Logger(Caught an exception: ," C:\log_file.txt")
    Logger(Exception Type:$type ","C:\log_file.txt")
    Logger(Exception Message: $Log_Message ,"C:\log_file.txt")
}


function Test_Exception()
{
    try
      {
        echo "This is test for exception "
        $global:Function_Exit_Status = $true
      }
    catch
      {
        Log_Exception $($_.Exception.GetType().FullName) $($_.Exception.Message) 
        $global:Function_Exit_Status = $false
      }
}