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. $PSshell = Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorVariable err -ErrorAction SilentlyContinue
  6. if($PSshell -eq $null){ Add-PSSnapin "Microsoft.SharePoint.PowerShell" }
  7. $fileName = "RKTest"
  8. $logFileName = $fileName + "_Log.txt"
  9. $invocation = (Get-Variable MyInvocation).Value
  10. $directoryPath = Split-Path $invocation.MyCommand.Path
  11. $logPath = $directoryPath + "\" + $logFileName
  12. $isLogFileCreated = $False
  13. function Write-Log([string]$logMsg)
  14. {
  15. if(!$isLogFileCreated){
  16. Write-Host "Creating Log File..."
  17. if(!(Test-Path -path $directoryPath))
  18. {
  19. Write-Host "Please Provide Proper Log Path" -ForegroundColor Red
  20. }
  21. else
  22. {
  23. $script:isLogFileCreated = $True
  24. Write-Host "Log File ($logFileName) Created..."
  25. [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
  26. Add-Content -Path $logPath -Value $logMessage
  27. }
  28. }
  29. else
  30. {
  31. [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)
  32. Add-Content -Path $logPath -Value $logMessage
  33. }
  34. }
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