PowerShell Posts

  • Mikael Riska (gravatar)

    I was recently contacted by one our customers with a request to change some permissions on some SharePoint sites. In normal cases this is something you can easily do through the user interface, only in this case they wanted to change the permissions on some 400 sites. And as you can probably imagine the permissions inheritance chain was broken or this would have been a trivial task. It is easy enough to programmatically loop through a bunch of SharePoint sites and set permissions but it felt overkill to fire up Visual Studio and create a throw-away console application that did this.

    No, this sounded to me like the kind of scripting tasks I remember from my old days on the IT admin side of the fence. I remember being blown away by the scripting capabilities provided by PowerShell when it was first introduced, but other than a few small tests on my own computer I never really had a good reason to use PowerShell in Real Life™ – until today, that is. I also remember reading about the possibility to use any .NET API available, surely this should be possible to pull of with a combination of PowerShell and the SharePoint API?

    Sure enough, a quick Google gave me a link to http://blogs.flexnetconsult.co.uk/colinbyrne/PermaLink,guid,1665700b-e0de-4b8a-bb1c-014d6fbcf2db.aspx where Colin Byrne explained how to import the SharePoint dll into PowerShell. That was all the help I needed since I already knew the SharePoint API and how to do what I wanted once I got at the correct objects. I immediately installed Windows Management Framework Core which contains PowerShell 2.0 and tested it out on my development server.

    [System.Reflection.Assembly]::Load(“Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c”)
    $spsite=[Microsoft.SharePoint.SPSite](“http://localhost/demo“)
    $rootweb = $spsite.RootWeb
    $group = $rootweb.EnsureUser("ECTEST\domain users")
    $role = $rootweb.RoleDefinitions["Contribute"]
    
    foreach($web in $rootweb.Webs)
    {
        $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
        $assignment.RoleDefinitionBindings.Add($role)
        $web.RoleAssignments.Add($assignment);
        
        $web.dispose()
    }

    Since I knew the SharePoint API reasonably well it was an easy task to throw together this script and test it out. After some head scratching I was able to pinpoint a couple of typos in my script and it finally worked as planned. Since PowerShell is not compiled it is easy to introduce typos and difficult to find them. All in all, the task was finished in about the same time it took me to write this blog post, and I know I will certainly revisit PowerShell for similar jobs in the future.