Thursday, July 28, 2011

Powershell script to use RunAs for SharePoint Add-Ins

I am in a environment where I want to use a Service Account ( say Farm account) for doing any command line task (for eg, add, install, retract solutions ….). In MOSS 2007, we used simple runas different user command to execute STSAM.

How am I going to achieve this, to use my lovely SharePoint Shell..

Anyway, i don't want to use Powershell profile because of some restrictions i have.

here is something I did..

1) Create a Powershell script with below entries and save it with RunAs.ps1

runas /user:domain\useraccount D:\MaintenanceScripts\Powershell\Runas\SPShell.Bat



2)Create a batch file named SPShell.Bat (you can name it as you wanted and ensure you update the same in the above RunAs.PS1) with the below content.

C:\Windows\system32\windowspowershell\v1.0\PowerShell.exe -NoExit " & ' C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\\sharepoint.ps1 ' "


Procedure to execute

1) Have both the files in a common folder
2) Create a shortcut of RunAs.ps1 to your desktop
3) Now double click on your RunAs.PS1 and work is done :)

If RunAS.PS1 opens in a notepad, use the following step.

i) Right click RunAs.PS1 and say open with and select Powershell, ensure you have selected "Always use the Selected program to open this kind of file"


Now you are ready to execute the SharePoint Shell as a different user (Farm admin).

Hope this helped you..

Sunday, July 3, 2011

Powershell script to monitor multiple SharePoint / IIS Sites

###########################################################################This script helps you in monitoring the availablity of your hosted sites
# and triggers an email for any IIS failures.
# It reads a file and executes the function for each URL's in the URL.txt # file
# written by KannaGanesh 03July11
###########################################################################

function SiteMonitor {
param($URL)
trap{
"Failed.Details: $($URL) $($_.Exception)"
$emailFrom = ""
# Seperate email addresses with comma's
$emailTo = ""
$subject = "$($URL) is un available"
$body = "$($URL) site is down around $endTime

Error Details

$($_.Exception)"
$smtpServer = ""
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
}
$webclient = New-Object Net.WebClient
$webclient.Credentials = [System.Net.CredentialCache]::DefaultCredentials
}

$startTime = get-date
$endTime = get-date
$webclient.DownloadString($URL) | Out-Null
}
$readfile = Import-Csv D:\MaintenanceScripts\URL.txt
foreach ($line.URL in $readfile){
sitemonitor $line.URL }

Points to Note
1) Ensure you are able to access those sites from the machine where this script will be scheduled
2) Provide the proper file location in $readfile, the URL.txt should be listing all url's under column URL. Something like below.
URL
http://1234.com
http://5678.com
3) This script reports problem based on any IIS errors.

Disadvantage

This script is not supporting for Web Application hosted on Claims Authentication.

Wish you all the best !

Wednesday, May 11, 2011

PowerShell script to backup site collections, write a log file and send a email for failures

Are you still using VB script to backup your site collection, come on dude…? It’s time to use the power of power shell...

There are lots of scripts published for backing up site collection, what special in mine??

Let me tell you what...

1) This script actually skip’s the failed site collection and report an email as well write in the log file.
2) The Log file will be written on either ways, whether the site got succeeded or failed.
3) One more final thing, I am using -Nositelock in my script. lol


#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# This script backups a list of site collection from a “text“ document and # writes to log file with URL in
# either case if it is succeeded or failed, it also sends a email on every # single backup failure with the
# Respective URL and exception
# Created by KannaGanesh May 10 2011
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

add-pssnapin microsoft.sharepoint.powershell
$date = (get-date).ToString()

# The below line reads the URL.txt file

$readfile = Import-Csv D:\URL.txt
$filepath

# The below four lines execute the backup and save in with URL Name (with Port # if available)

foreach ($line.URL in $readfile)
{$FilePath = “D:\backups\” + $line.Url.Replace("http://",””).Replace(“/”,”-“).Replace(":","-") + “.bak”;
backup-spsite -identity $line.URL -path $filepath -nositelock -force -errorVariable a -ea SilentlyContinue ;
$a

# The below if / else statement will write the log files and send a email for any failure

If ($a -ne $null)
{write-output "$date Backup failed for $line.URL with" $a | out-file D:\log.txt -append ;
$emailFrom = "from@example.com"
$emailTo = "emailed@example.com"
$subject = "Sitecollection Backup failed"
$body = "$line got failed, Please check the log files @ D:\log.txt for more details"

# Use commas for multiple addresses

$smtpServer = "Your SMTP Address"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)}
else
{write-output "$date succcess $line" | out-file D: \log.txt -append}
}


Ensure the following
1) Before executing this script, ensure you eliminate any unwanted spaces or # signs
2) Ensure your URL.txt file is in below format.
URL
http://URL1
http://URL2
http://URL3
3) Make sure your script has access to Url.txt and log.txt files,
4) Hope you have a valid SMTP service which can sent emails when there is a failure

Disclaimer

We have tested this script in our environment and confirmed to be working fine, please execute the same in dev / test environment before moving in to production to avoid any damage

Wish you all the success.

Tuesday, May 10, 2011

Poweshell script to install and activate Feature in SharePoint 2010

People who say, Boss I am fed up typing this powershell / STSADM command to Install the features... can we make it easy somehow ???

Yes buddy, here you go... Copy the below script and your done!

################################################################################################################################################
# This Powershell script helps you to install and activate features for
# your webapplication / site collection
# If the feature already exist then this will deactivate, uninstall then
# Install and enable, based on your requirment
# Created By Kannaganesh, dated 03-May-11
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++

# remove "#" in the below line, if you are not running this script in
# SharePoint Shell.This will install Powershll snap-ins for Sharepoint
# add-pssnapin microsoft.sharepoint.powershell

# Below line reads your keyboard input for feature folder name

$FolderName = read-host "FeatureFolderName"

# Below line reads ur keyboard input for URL

$URL = read-host "URL"

# Next two lines check for the availablity of the feature which you are about to install

$getfeature = Get-SPfeature | where-object {$_.DisplayName -eq "$foldername"}
$getfeature
If ($getfeature -eq $null)

# Below two lines installs the feature if it is not already installed.

{Install-SPFeature $folderName -force;
Enable-SPFeature $FolderName -url $URL;
write-output "$folderName is installed and enabled for $url" }

# If Yes the following else statment will disable, uninstall then Install # and enable the feature to your site

else

{disable-spfeature -identity $foldername -url $url ;
start-sleep -s 5 ;
uninstall-spfeature -identity $foldername;
start-sleep -s 5 ;
Install-SPFeature $folderName -force;
start-sleep -s 5 ;
Enable-SPFeature $FolderName -url $URL ;
write-output "$folderName is re-installed and enabled for $url"
}

Consideration

1) The feature folder is available on all the servers in your farm.
2) The feature your trying to install / activate is a farm based and not server based.
3) If it is server based, this needs to be executed on all servers in farm.

Procedure for executing this script

I am sure, most of you know, how to execute this script. For folks, who need assistance follow the below steps.

1) Copy the above script to a notepad and save it as Installfeature.ps1 (you can use your defined file name with ext .ps1). Ensure, you elimenate space or extra "#" in the copied script, if any.

2) Open SharePoint Shell as Administrator.

3) Navigate to the folder, where your script is placed.

4) Now its time to execute, .\installfeature.ps1 (this can be easily achieved by .\In and a tab).

5) You will be prompted for folder name and URl values one after other.

6) What next, if your feature is not existing. It silently installs and "tells you BOSS your done !"

7) If It is existing , then you will be prompted for your approval to continue / cancel.

Hope this helps...

Disclaimer :-

This script is tested in few env and found to be working, please try the same in your dev/test env before moving in to production.

Good luck :)