I wrote my very first PowerShell script today which I wanted to share. I’m definitely no PowerShell guru; in fact, the only times I’d ever used Powershell before is to run a script someone else has written. I have never written even one line of a PowerShell script before but I had to do so today. Basically, I needed to write something to quickly turn all my MOSS 2007 site collections into read-only mode. Since we’re talking about hundreds of site collections here, there was no way I was going to do this manually. In Service Pack 2 for WSS/MOSS, the setsitelockSTSADM operation was added to allow you to specify a lock type on a site collection. I knew I could use this and combine it with the enumsitesSTSADM operation to quickly turn my site collections into read-only mode and then later turn it back into ‘normal’ mode.
Below is my script. Remember that again, this is my first PowerShell script and I needed to get it done quickly so be gentle in the critique ;).
Script: setsitelock.ps1
1: param([string]$lockmode, [string[]]$webappurls)
2:
3: $arrLockModes = "none", "noadditions", "readonly", "noaccess"
4:
5: if ($lockmode -eq "" -or $webappurls -eq $null)
6: {
7: Write-Host -foregroundcolor red "Either lockmode or webappurls not specified. Usage: setsitelock -mode {none|noadditions|readonly|noaccess} -webappurls url1,url2,url3"
8: }
9: elseif ($arrLockModes -notcontains $lockmode)
10: {
11: Write-Host -foregroundcolor red "Incorrect -lockmode specified. Valid lockmodes are: $arrLockModes"
12: }
13: else
14: {
15: foreach($webappurl in $webappurls)
16: {
17: Write-Host "Setting site lock for site collections in $webappurl to $lockmode."
18: $rawdata=stsadm -o enumsites -url $webappurl
19: $sitesxml=[XML]$rawdata
20:
21: foreach($site in $sitesxml.sites.site)
22: {
23: $scurl= $site.url
24: Write-host -foregroundcolor yellow "`tSite collection: $scurl"
25: $msg = stsadm -o setsitelock -url $scurl -lock $lockmode
26:
27: if ($msg -match "Operation completed successfully") {$fgcolor="Green"}
28: else {$fgcolor="Red"}
29:
30: Write-host -ForegroundColor $fgcolor "`t`t$msg"
31: }
32: }
33: }
To run the script, just save the script to a directory, open up the PowerShell console, navigate to the directory and run:
.\setsitelock.ps1 –lockmode {none|noadditions|readonly|noaccess} –webappurls “app_url_1”, “app_url_2”, “app_url_3”, etc.
The actual file: setsitelock.zip (624.00 bytes)