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

  1. Leave a comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: