PowerShell Snippets

PowerShell Snippets

As Premier Field Engineers, we often find that our customers need assistance creating PowerShell scripts that can help automate administrative processes; or retrieve information from their various SharePoint farms.

Whilst each of our customers are different and have unique environments; many scripts have requirements that are similar, if not the same regardless of the environment or the actions that the script will perform.

This blog post (the first of a series of blog posts that I am aiming to write) takes a look at some of these common scripting requirements, with the aim of providing you with some useful ‘snippets’ of code. As with all blog posts that we write, the code has not been tested in your environment, so do use caution and fully test anything that you use.

 

(1) Event Logging

“When we run a script; we want to ensure that we log/ capture who runs it in the server event log…”

This requirement is pretty common. Being able to keep a record of who is running what on your servers is useful; not just for those ‘oops’ moments, but really useful in general :)

 

Script example: Creating a new entry in the Application Log

# Get the current logged in user

$userObj = [System.Security.Principal.WindowsIdentity]::GetCurrent()

$user = $userObj.name

# Set up the event log variables

$eventLog = Get-EventLog –List | Where-Object {$_.Log –eq ‘Application’}

$eventLog.MachineName = “.”

$eventLog.Source = “Contoso IT Department”

# Write an entry into the Application Log

$eventLog.WriteEntry(“The script was started by $user.”,”Information”,2014)

Fig 1: Log entry created in Application log

Fig 2: Log entry detail

 

(2) Showing Script Progress

“When we run the script, we want to be able to see its progress rather than stare at a blinking cursor…”

This is a pretty common requirement too; especially on scripts that query a large collection of objects. The good news is that PowerShell provides us with a great cmdlet to do just this (Write-Progress):

Script example: iterating through all sub-webs in a site collection

$collWeb = Get-SPWeb –identity https://intranet.contoso.com/sites/sitecollection1

[int]$i = 0 

Foreach ($web in $collWeb) {

    $i++ Write-Progress –activity “Collecting all sub webs” –status “Status: “ –percentComplete (($i / $collWeb.count)*100) }

Fig 3: Showing progress bar

 

That’s all for now, I hope that this has been useful.

Cheers, Steve
@moss_sjeffery