Scripting STSADM with PowerShell

April 28 2010 31 comments

(Update: I had forgotten to specify the -apidtype parameter for the extendvs command. That’s fixed now.)

For this article, I’m assuming at least a vague familiarity with PowerShell. If you have no idea what I’m talking about, there are plenty of resources on TechNet, and some great tutorials by our CTO, Jouni Heikniemi to get you started.

Recently I found myself in a phase of development, where I would try out some modifications to content types, notice that they weren’t what I wanted, and then re-do the entire web application from scratch to make sure my next modifications would be picked up by SharePoint. As you can probably imagine, doing that via the administrative interface got old quickly, so I decided I’d do my best to automate the process.

While SharePoint 2010 ships with a wide variety of PowerShell cmdlets for your scripting pleasure, those SharePoint 2007 installations aren’t going anywhere in some time. This is also a good way to get comfortable with PowerShell, if you don’t have any 2010 projects to work with. :-)

First off, let’s set up some variables and aliases to ease our job:

$webAppUrl = http://testwebapp.localhost
$webAppUrlWithPort = "${webAppUrl}:80"
$appPoolUser = "TESTDOMAIN\username"
$appPoolPass = "password"
$dbName = "SharePoint_${env:computername}_Content_TestWebApp"
$ownerEmail = "nobody@example.com"
$siteCollectionUrl = "$webAppUrl/siteCollection"

set-alias STSADM "${env:commonprogramfiles}\Microsoft Shared\Web Server Extensions\12\BIN\STSADM.EXE"

Now we’ve got most of the information we need for the various commands we’re about to run. Next up, call STSADM to create the web application:

echo "Creating web app"

STSADM -o extendvs `
    -url "$webAppUrlWithPort" `
    -sethostheader `
    -ownerlogin "$appPoolUser" `
    -owneremail "$ownerEmail" `
    -databaseserver "$env:computername" `
    -databasename "$dbName" `
    -apidtype ConfigurableID `
    -apidname "TestWebApp app pool" `
    -apidlogin "$appPoolUser" `
    -apidpwd "$appPoolPass" `
    -donotcreatesite
iisreset

(Pay attention to the backticks at the end of each line – it’s the PowerShell escape character, and it must be the last character on a line in order to work as a line continuation character.)

As nice as this is, it’s not exactly earth-shattering. In fact, all this could be done just as well with a BAT file. So why bother with PowerShell?

The first problem comes when we want to run this more than once. If I create the site and it already exists, things might get ugly. Then again, if I try to delete it and it doesn’t exist, I’ll get an error message. But where there is a shell, there is a way. STSADM has a habit of returning most of its interesting information as XML, and as it happens, PowerShell is rather adept at handling XML:

$webApps = [xml](STSADM -o enumalternatedomains)

I’m invoking the STSADM command “enumalternatedomains”, which lists the web applications we’ve got. It returns a bunch of XML tag soup, but the [xml] cast parses the STSADM output and gives us an object that reflects the structure of the XML document.

$matchingApps = $webApps.AlternateDomains.Collection `
    | foreach { $_.AlternateDomain } `
    | where { $_.IncomingUrl -eq "$webAppUrl" }

Here I’m walking the child items of the XML we got, filtering out only the ones where the URL matches the site we’re trying to create. Now we have a clue as to whether we’ve got something to delete:

if($matchingApps) {
    echo "Removing old app instance"

    STSADM -o unextendvs `
        -url "$webAppUrlWithPort" `
        -deletecontent `
        -deleteiissites

    iisreset
}

Now that we’ve got a web application up and running, let’s add a managed path and create a site collection:

echo "Adding managed path $siteCollectionUrl"
STSADM -o addpath `
    -url "$siteCollectionUrl" `
    -type explicitinclusion

echo "Creating $siteCollectionUrl"

STSADM -o createsite `
    -url "$siteCollectionUrl" `
    -lcid 1033 `
    -owneremail "$ownerEmail" `
    -sitetemplate "TestWebApp.Publishing#1" `
    -ownerlogin "$appPoolUser"

And finally, if we need to activate features:

echo "Activating Master Page feature"

STSADM -o activatefeature `
    -name "TestWebApp.MasterPages.Default" `
    -url "$webAppUrl"

(Note: I’ve tried to consistently quote all the string arguments I’m passing to STSADM, even when it isn’t strictly necessary. For the most part, you could do without the quotes. Also, if you’re wondering why I sometimes say “${webAppUrl}” instead of “$webAppUrl”, the former form is necessary when the variable is inside a string, and directly followed by a character that could be part of the variable name.)

We didn’t go deep into PowerShell here yet, merely spicing up a bunch of STSADM calls with some niceties – but this is just the beginning. In the near future, I’m going to show you how to implement your own PowerShell commands for manipulating things like master pages. Stay tuned!

Popularity: 3% [?]

31 comments to “Scripting STSADM with PowerShell”

  1. [...] my previous entry on SharePoint and PowerShell I promised I’d show you how to implement custom commandlets for Master Page manipulation. [...]

  2. tylerrrr07 says:

    Very helpful! Managed to script together a Migrate Users script with this so that it migrates all users meeting a certain criteria instead of manually one user at a time.

    Thanks for sharing!

  3. Yalin Meric says:

    For some strange reason this method does not work in Sharepoint 2010 Powershell. The parameters supplied to stsadm alias are handled as null values and the script throws exception:

    Command line error.

    The command line is:

    stsadmalias –o migrateuser –oldlogin “$AccountName” –newlogin “$NewAccountName”

    where stsadmalias is the alias for stsadm, $AccountName and $NewAccountName are two string parameters set correctly before this line. What may I be missing?

  4. mark says:

    Thanks lads, this will come in handy

  5. Hank says:

    Do you happen to know how to convert enumsites output to CSV file?

  6. great insight. Really enjoyed browsing this blog. Keep up
    the good work and to everyone keep on learning!

    Also visit my homepage; free psn points

  7. discussion about this piece of writing here at this blog, I have read all that, so
    now me also commenting at this place.|
    I am sure this piece of writing has touched all the internet visitors,
    its really really good article on building up new webpage.|
    Wow, this article is good, my sister is analyzing these kinds of things, so I am going to convey her.|
    bookmarked!!, I really like your website!|
    Way cool! Some extremely valid points! I appreciate you

    mysite:http://www.whiteswancottages.com/?page_id=3

  8. pk seuraa says:

    Today, while I was at work, my cousin stole my
    iphone and tested to see if it can survive a thirty foot drop, just so she can be a
    youtube sensation. My iPad is now destroyed and she
    has 83 views. I know this is completely off topic but I had to
    share it with someone!

  9. Today, I went to the beachfront with my children. I found a sea shell and gave it
    to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed.
    There was a hermit crab inside and it pinched her ear. She
    never wants to go back! LoL I know this is entirely off topic
    but I had to tell someone!

  10. Mariano says:

    Hi there! Someone in my Facebook group shared this site
    with us so I came to look it over. I’m definitely loving the information. I’m book-marking and
    will be tweeting this to my followers! Terrific blog and excellent design.

  11. tatuoinnit says:

    Wow that was strange. I just wrote an extremely long comment but after I clicked submit my comment didn’t show up.
    Grrrr… well I’m not writing aall that over
    again. Regardless, just wajted to say fantastic blog!

  12. Hurrah, that’s what I was exploring for, what a
    material! existing here at this web site, thanks
    admin of this web site.

  13. Wow, this article is good, my younger sister is analyzing
    these things, therefore I am going to convey her.

  14. Hi there, i read your blog occasionally and i own a similar one and i was just curious if you get a lot
    of spam feedback? If so how do you prevent it, any plugin or anything you can recommend?

    I get so much lately it’s driving me crazy so any help is very much appreciated.

  15. It’s amazing for me to have a site, which is good for my experience.

    thanks admin

  16. great issues altogether, you juyst received a logo new
    reader. What may you recommend iin regards to your publish that you just made some days ago?
    Any certain?

  17. Somsbody necessarily lend a hand to make seriously articles I would state.
    That is the first time I frequented your web page and upp to now?
    I surprised with thee analysis you mwde to create this actual post incredible.
    Wonderful process!

  18. Seine , wie Sie lesen thoughts! Sie scheinen erscheinen, zu
    verstehen eine Menge etwa, wie du schrieb das Buch e-book drin oder so etwas.

    Ich denke,, dass man einfach können Sie mit einige PC bis Macht
    die Nachricht home ein bisschen, aber statt, dass dies Blog.
    Eine fantastische lesen. Ich sicherlich wieder.

    Ich bin nicht sicher, wo Sie Information, aber guten Thema.
    Ich muss einige Zeit damit verbringen, mehr oder viel mehr Verständnis mehr.
    Vielen Dank für fantastischen info Ich war für diese Suche
    Information für meine Mission. und mit

    Wenn jemand schreibt eine Artikel er / siee hält Plan eines Benutzers
    in seine / ihre Meinung Das Gehirn, wie man user
    kann verstehen Also Daher das ist, warum diese Absatz perfekt.
    Vielen Dank Website ‘s Post regelmäßig aktualisiert werden
    Hallo jeder hier jeder teilt Diese Art von Wissen Ich weiß es ist schön, dies zu lesen Homepage, und ich pflegte, einen Besuch abstatten diese blog
    daily für Blog, ich Ihnen von Fehler gefunden etwas anderes, Irgendwie Ich bin jetzt hier und möchte nur sagen, vielen Dank prost enormen Beitrag und eine rundum spannende unterhaltsam Blogs (ich
    liebe auch das Thema / Design), ich habe keine
    Zeit, um zu lesen, durch Z alles auf die Minute Moment, aber ich habe
    Buch-Kennzeichnung gespeichert und es auch aufgenommen in Ihre RSS-Feeds hinzugefügt, so, wenn ich Zeit habe werde ich
    zurück sein, las sehr mehr, Bitte halten Sie die superb jo.

    für Blog, ich Ihnen von
    Das ist sehr wirklich interessant, Sie sind eine sehr professionelle qualifizierte Blogger.
    Ich habe beigetreten Ihren Feed und bleiben für wir suchen ausgezeichnete
    Post. Auch Außerdem, ich site in meinem sozialen Netzwerken

  19. Hey there! I just wanted to ask if you ever have any issues with hackers?

    My last blog (wordpress) was hacked and I ended up losing months of hard work due to no backup.
    Do you have any methods to protect against hackers?

    My webpage – Jurassic Park Builder Cheats Hack

  20. I have fun with, lead to I found exactly what I used to be having a look
    for. You’ve ended my four day long hunt! God Bless you man. Have a nice day.
    Bye

  21. hello!,I like your writing very much! proportion we keep up a correspondence more about your article on AOL?
    I require a specialist in this house to resolve my problem.
    Maybe that’s you! Having a look forward to look you.

  22. Hi there mates, its wonderful article on the topic of teachingand fully defined, keep
    it up all the time.

  23. The lower the cost of porting the software in relation to
    its implementation costs, the more portable it is. Why you
    should choose a large company that all the parts for Android app development, and meet
    your requirements. There is nothing completely wrong with the desire to be a
    part of the growing developers’ community.

  24. I must thank you for the efforts you’ve put in penning this website.

    I really hope to view the same high-grade blog posts by you later
    on as well. In truth, your creative writing abilities has inspired me to get my own blog now ;)

  25. Just stop in on An Open Track Day, it is the opportunity for you to drive
    your car or bike on the racetrack. It doesn’t mean all the driving schools offer a quality driving instructor, since some of the
    driving schools offer courses just for their revenue.
    The Driving Test results in the Limerick and Mid-west area generally have been at the higher end of
    the scale for several years in contrast with other parts of the country that haven’t
    fared so well in pass rates.

  26. Utilizziamo moderni ed fidati metodi per la femminizzazione dei nostri semi.

  27. Felice Tuell says:

    Can I just say what a relief to find someone who actually knows what they are talking about. You definitely know how to bring an issue to light and make it important. I cant believe you are not more popular because you definitely have the gift. Best Hosting Best Hostwinds Review

  28. Warren says:

    In the event that coloring books of yesterday are fading away, coloring pages for young
    ones on the web have actually surely taken their spot.

    For more topics find out more about winnie the pooh halloween coloring pages printable (Warren)

  29. Anders Johnsson says:

    Send me emails.

  30. That would be fine if it was just me utilizing the iPad, but presently it
    is just the toddlers working with the tablet.

    my web page learn your colors in spanish

Leave a Reply