How to Log Errors When Using PowerShell With SharePoint 2010 and 2013

When writing in C# it is a good practice to log any errors in the event log. But, when executing scripts with PowerShell in SharePoint, most developers ignore how to log errors or messages. This article will concentrate on how to do logging with PowerShell.

Main Points Covered
 
The following are the main points covered:
  • How to handle exceptions with PowerShell in SharePoint
  • How to log exceptions with PowerShell in SharePoint
  • How to log messages with PowerShell in SharePoint
Other Points to Observe
 
Other points to be observe are:
  • Generic method to log exception
  • How to decorate any exception messages that comes with foreground colors (this will be more impressive for the eyes)
  • How the site object can be created
  • How a variable of a specific type can be created (most of the developers are not aware of this)
This is relevant to both SharePoint 2010 and SharePoint 2013. The following is sample source code:
 

$DATE = get-date

$LogPath = "D:\Custom\Projects\MyTeamSite"

$LogFileName = "MyTeamSiteLog.log"

 

$FilePath = $LogPath +"\" + $LogFileName

 

$logFileCreated = $False

function write-log([string]$label, [string]$logMsg)

{

    if($logFileCreated -eq $False)

    {

        write-host "Creating log file..."

        if((Test-Path -path $LogPath) -ne $True)

        {

            write-host"Provide proper values to LogPath folder" -ForegroundColor Red

        }

        else

        {

            Add-Content -Path $FilePath -Value $logHeader

            $script:logFileCreated  = $True

            write-host"Log file created..."

        }

    }

    else

    {

        [string]$info = [System.String]::Format("[$Date] {0}: {1}",$label, $logMsg)

        Add-Content -Path $FilePath -Value $info

    }

}

 

try

{

    $siteUrl = "http://MyTeamSite"

    write-log"Accessing web with url" $siteUrl

    $web = Get-SPWeb -identity $siteUrl

}

catch

{

write-host"Error: Please check the log file"  -ForegroundColor Red

write-log ("!!ERROR!!",$error[0])

}

Overview


In the above code, you can see that the generic method "write-log" is used to log messages and exceptions.
 
Provide values to the variables as in the following:
  • $LogPath: Location of the log folder 
  • $LogFileName: Name of the log file that will be created

Conclusion


When ever your script is executed, we will see in the log file the success messages and exceptions, if any. In general, for SharePoint when a script is given to the deployment team we can just specify that the changed variable values are logged. We can then observe the log file after completion of the script.
 
This is a standard and better way that most developers will ignore. Sometimes, people are not aware of this.
 
Hope this article gives insight to the standards as well as good features of PowerShell in SharePoint.

Up Next
    Ebook Download
    View all
    Learn
    View all