Archive for October, 2011

PowerShell Script tips: Writing to a log file and checking for a PSSnapin

A couple of tips that I gleaned while writing PowerShell scripts:

    1. To write output to a file, use the “Write-Output” command like this: “Write-Output $log_text” and when executing the script, pipe the output to a file like so:

PS C:\> psscripts\coolscript.ps1 | Out-File C:\psscripts\ps.log

2. Sometimes I run scripts from within the Windows PowerShell Integrated Scripting Environment (ISE) and other times from the SharePoint 2010 Management Shell.  To avoid the error of re-adding the SharePoint snapin, I use this code to check if it has already been loaded:

$powershellSnapin = “Microsoft.Sharepoint.Powershell”
if ((Get-PSSnapin -Name $powershellSnapin -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin $powershellSnapin
}

Leave a comment