Creating Log file in PowerShell Script

Overview

Today I thought I can share something which is commonly used and very use full information in developing the scripts and validating the scripts.

So I am writing the standard function which is commonly used that is How to Create Log file in PowerShell Script.

Why Log File?

Using log file people can follow, and can see what is happening while the script is executing and records the errors if any, and also it improve the debugging steps and makes life easier.

Script Code

  1. [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")  
  2. [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Publishing")  
  3. [System.Reflection.Assembly]::LoadWithPartialName("System")  
  4. [System.Reflection.Assembly]::LoadWithPartialName("System.IO")  
  5.   
  6. $PSshell = Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorVariable err -ErrorAction SilentlyContinue  
  7. if($PSshell -eq $null){ Add-PSSnapin "Microsoft.SharePoint.PowerShell" }  
  8.   
  9. $fileName = "RKTest"  
  10. $logFileName = $fileName + "_Log.txt"   
  11. $invocation = (Get-Variable MyInvocation).Value  
  12. $directoryPath = Split-Path $invocation.MyCommand.Path  
  13. $logPath = $directoryPath + "\" + $logFileName   
  14. $isLogFileCreated = $False   
  15.   
  16. function Write-Log([string]$logMsg)  
  17. {   
  18.     if(!$isLogFileCreated){   
  19.         Write-Host "Creating Log File..."   
  20.         if(!(Test-Path -path $directoryPath))  
  21.         {  
  22.             Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
  23.         }   
  24.         else   
  25.         {   
  26.             $script:isLogFileCreated = $True   
  27.             Write-Host "Log File ($logFileName) Created..."   
  28.             [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
  29.             Add-Content -Path $logPath -Value $logMessage   
  30.         }   
  31.     }   
  32.     else   
  33.     {   
  34.         [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
  35.         Add-Content -Path $logPath -Value $logMessage   
  36.     }   
  37. }   
Write-Log "Start of the program..."
Write-Log "Created By : Ramakrishna Basagalla"
Write-Log "End of the program..."

Executing the PowerShell Script

PowerShell Script

Output File

Log File

Log File Content

Log File Content
Ebook Download
View all
Learn
View all