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
- 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)
$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.
- $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.

Adiseshu DasariPosted Jan 17, 2013, 9:28 AM
Thanks Dinesh
Dinesh BeniwalPosted Jan 17, 2013, 8:07 AM
Good Start, Welcome to the C# Corner.