Tuesday, June 16, 2009

You know how it is, you start developing a project and then 6 months later you look back and realise you have to document everything you've produced.

I've just gone through that process and need a quick list of all the features ids scattered around various subdirectories of a large project.

sample:

<Feature  Id="886f12cf-97ca-4789-baf8-6f13f9f2cedf"
          Title="PGPSO Contract Management Project Upgrade"
          Description="Feature that upgrades Project Sites for Contract Management."
          Version="12.0.0.0"
          Hidden="FALSE"
          Scope="Web"
          DefaultResourceFile="core"
          ReceiverAssembly="PGPSO_CM_Project_Upgrade, Version=1.0.0.0, Culture=neutral, PublicKeyToken=aa0408b86137366a"
          ReceiverClass="PGPSO_CM_Project_Upgrade.PGPSO_CM_Project_Upgrade"
          xmlns="http://schemas.microsoft.com/sharepoint/">

Firing up Powershell navigating to the root of the solution folders and running this command gets me the list

gci -recurse -filter  feature.xml | % { $contents=get-content $_.fullname; $x=[XML]$contents; "{0} {1}" -f $x.Feature.Id, $x.feature.title }

result:

 

gci is an alias for get-childitem which allow you to recurse subfolders and provide a filter parameter. Then use get-content to open the file, convert to an XML object and then directly reference the Id and title of the feature.xml file.

 

 

Tuesday, June 16, 2009 2:10:27 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [2]  | 
 Wednesday, April 02, 2008

The UK Microsoft User Groups have organised another huge gathering at Microsoft Reading next week.

This time it's split over 2 days April 8th and 9th and features a lot of great sessions. User groups that I'm active in such as the UK SharePoint user group, PowerShell user group and the Vista squad will be there along with the user groups for Exchange, SQL Server and others.

It's not often you get a host of experts on these subjects in one location so check out the agenda and see if any sessions take your fancy.

I'm doing a session on day 2 crossing over two groups SharePoint and PowerShell on moving data in SharePoint using the Content Deployment API (aka Prime API) and PowerShell. I'll go through some of the functions and cmdlets I've written to make moving data easier, samples include moving list items, lists, webs and site collections within and between farms.

Wednesday, April 02, 2008 1:28:02 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, March 21, 2008

Zach Rosenfield has a nice post on calling WebServices from PowerShell. The steps are pretty simple: generate a proxy cs file, compile it into a DLL and then load that DLL up into Powershell AppDomain.

Well I've been doing some work with quite a few of the WebServices and I wanted to compile all the proxys into a single DLL.

Use Zach's post to setup the PowerShell environment variables needed to call the Visual Studio SDK utilities wsdl.exe and csc.exe

Heres the script to compile all the available SharePoint Webservice's into one DLL.

It simply enumerates all the ASMX files in the ISAPI directory and passes each item in that list to WSDL.exe which generates the proxy cs files.

You need to change the URL in this script to point to a valid SharePoint site and make sure there are no other .cs files in the directory before running this script.

$asmxlist= dir "C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI" *.asmx | select name

$asmxlist | foreach-object {
write-host "Generating SharePoint Proxy Library for $($_.name)" -foregroundcolor green 

$outputfilename="FlexnetConsult.SharePoint.$($_.name).cs"
$namespace=[IO.Path]::GetFileNameWithoutExtension($_.name)

wsdl "http://portal.contoso.com/matters/sites/_vti_bin/$($_.name)" /o:$outputfilename /namespace:$namespace

}

write-host "Compiling SharePoint Proxy Library" -foregroundcolor green 
csc /t:library /out:FlexnetConsult.SharePoint.WebServices.dll *.cs 

 

So the output should be something like this

 

image

 

Now three of the WebServices generate an error SlideShow.asmx. FormserverProxy.asmx and contentareatoolboxservice.asmx but as I'm unlikely to use them I'm not going to worry about those.

So now we have a DLL called FlexnetConsult.SharePoint.WebServices.dll in our directory that we can use to call the (almost) any SharePoint Web Service.

I've attached the compiled dll and script.

In my next post I'll use the DLL to do something I've wanted to do for ages and that's list, add and delete Web Parts on a page using PowerShell.

Now your probably shouting, hey why not just call the object model and GetLimitedWebPartManager, yep but that doesn't work as without a web.config and possibly a HttpContext all you get back are Error WebParts as the WebPart safecontrollist cannot be accessed.

 

 

Friday, March 21, 2008 7:59:44 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
 Monday, February 25, 2008

I forgot to post this before but Microsoft has created a virtual lab based on my blog postings. If you're interested in Powershell and SharePoint its definitely worth checking out

http://msevents.microsoft.com/CUI/WebCastEventDetails.aspx?EventID=1032346304&EventCategory=3&culture=en-US&CountryCode=US

As noted on Ben Pierce's blog Powershell is now a CER common engineering requirement for all products released in 2009 and beyond, that should mean as Office 14 is due for release in 2009 PowerShell should be a mandatory feature in SharePoint.

Thats good news and a big change as when I'd asked the question about PowerShell support in SharePoint to Mike Fitzmaurice back in February last year the answer was they had no plan to do so.

Monday, February 25, 2008 12:12:27 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Friday, June 15, 2007

I’m presenting at the EVO (Exchange, Vista, Office) Community day next Thursday the 21st June.


I’ll be doing a session that shows how you can use Powershell to read information from Exchange and getting it into SharePoint 2007.
Its really hard to know how to pitch a presentation like this as the mix of experiences is probably going to be wide, from people seeing this stuff for the first time to old hands. Anyway I’m looking forward to it.

The talk will cover some Powershell basics, calling the new Exchange Web Services from PowerShell and why we might still need to use WebDAV(hint Public Folders) and of course how we write to SharePoint.
I'll start posting some of the code samples over the next week.

There’s lots of other sessions including ones from Steve Smith on SharePoint and Richard Siddaway on PowerShell, should be a good one.

Heres the details of the Event:
The Next EVO Community Day - June 21st: Microsoft Campus Thames Valley Park Reading

Event Agenda
09:30 Start
09:30 - 10:00 Keynote
10:00 - 10:25 Introductions to groups (Including LiveMeeting, Longhorn, Virtualisation)
10:25 - 10:55 Vista
10:55 - 11:10 Break
11:10 - 12:40 Office, SharePoint, Groove
12:40 - 13:25 Lunch
13:25 - 14:55 Break-out sessions
14:55 - 15:10 Break
15:10 - 15:40 OCS + UM
15:40 - 16:40 Exchange and PowerShell
16:40 - 16:55 Break
16:55 - 17:30 Q&A

Further agenda information can be found here:  http://www.ukusergroups.co.uk/Agenda.html

To sign up and more information: http://www.ukusergroups.co.uk/

 

Friday, June 15, 2007 9:57:30 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, March 14, 2007

I’m presenting at the next UK PowerShell User Group meeting on March 22nd doing an updated talk around using PowerShell with SharePoint featuring an intro to PowerShell,  Demos and roundup with SharePoint/PowerShell gotchas and 'tips and tricks'.

The talk should be be of interest of anyone who might like to talk to a managed API with Powershell.

I’m doing the first talk and Richard Siddaway is doing the second session with a talk on using ActiveDirectory with PowerShell.
If you need an intro to using PowerShell or want or ask more advanced questions this will be a good place to be.

Location:
Memphis Room
Microsoft Building 3
Thames Valley Park
Reading

Registration 18:00
Start           18:30

You need to register for attendance so follow the instructions in this link: http://www.culminisconnections.com/sites/get-psuguk/Lists/Events/DispForm.aspx?ID=2

Hope to see you there.

Wednesday, March 14, 2007 2:29:09 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
 Saturday, February 10, 2007

 

Following on from the work in my previous post where I set the users Picture property in their profile the next step is to add a Contact Web Part to our imported publishing pages. I’m using the default layout page to add the contact Web Part to, this page has the Web Part Zones underneath the content fields but you could use another layout that has a Web Part zones to the right of the content fields and of course you can use SharePoint Designer to create your own layout formats and embed the Contact control without using code.

This is how our publishing pages will look once we have added the Web Part to each page

An interesting feature of a Publishing page is that it has a contact property where you can assign user details to each page, you can either lookup the user from the picker in which case the page will pull the users details from the profile database or you can type in the details yourself.

 

The nice thing about the Contact Web Part is that once you have added it to a publishing page it will automatically pull the picture and the users description (if set in the Web Part) that has been assigned to the page from the profile database.

One bad thing about the part is you only get the choice to put the users name left or right not top or bottom.

So on to the code, I need a function that will take a site URL and then set the default Publishing Page’s contact property and then add the Web Part to the page.

 

 

# Function: Add-ContactWebPart # Description: Adds the Contact User Web Part to a publishing page # Parameters: SiteURL - Server relative URL of the Area # UserName - UserName to show as the contact in domain\user format # # Requirements: Needs to have the System.Web assembly loaded # function Add-ContactWebPart($SiteURL, $UserName) { $comment = "Contact WebPart Added" $site = new-object Microsoft.sharePoint.SPSite($SiteURL) $web=$site.OpenWeb() $user= $web.Users.get_item($UserName) $pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web) $defaultpage=$pubweb.GetPublishingPages()[$pubweb.DefaultPage] $defaultpage.CheckOut() # Set Contact "Setting Contact on " + $pubweb.url + " to " + $user.Name $defaultpage.set_Contact($user) $defaultpage.Update() $webpartmanager=$web.GetLimitedWebPartManager($defaultpage.Url, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared) $webpart=new-object Microsoft.SharePoint.Portal.WebControls.ContactFieldControl $webpart.ChromeType=[System.Web.UI.WebControls.WebParts.PartChromeType]::TitleOnly; $webpart.Title="Page Contact" $webpart.PicturePosition=[Microsoft.SharePoint.Portal.WebControls.PictureDirection]::Left $webpart.IsDisplayJobTitle=$true $webpart.IsDisplayPicture=$true $webpartmanager.AddWebPart($webpart, "LeftColumnZone", 0); " Checking in page" $defaultpage.CheckIn($comment) # Publish if($defaultpage.listItem.ParentList.EnableMinorVersions -eq $true -and $publishingPage.ListItem.File.MinorVersion -ne 0) { " Publishing" $defaultpage.listItem.File.Publish($comment) } # If moderation is being used handle the approval if ($defaultpage.listItem.ParentList.EnableModeration) { $modInformation = $defaultpage.listItem.ModerationInformation " Moderation on, Current Status: " + $modInformation.Status # Check for pending approval if($modInformation.Status -ne [Microsoft.SharePoint.SPModerationStatusType]::Approved) { " Approving" $defaultpage.ListItem.File.Approve($comment) } } # Clean up $pubweb.Close() $web.Close() $site.Close() }

 

In this code we find the SPUser object for the given username and set the Contact property of the PublishingPage to it. We then add the web Part using the new SPLimitedWebPartManager class. Most of the code is concerned with checking the page out and back in and assumes the page is not already checked out.

An interesting line is

$defaultpage=$pubweb.GetPublishingPages()[$pubweb.DefaultPage]

I'm indexing into the collection return by GetPublishingPages because Powershell doesn't support generics in the current version.

Saturday, February 10, 2007 8:17:59 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, January 28, 2007

Now we have the portal setup I want to add a Contact WebPart to each page but before I can do that I have to add a picture for each user I have imported, in order to keep this post a little shorter I’m only going to concentrate on using the UserProfile API’s to set our picture for each user.
(The Contact WebPart is MOSS WebPart that shows a users name and description and optionally their picture)
The field that we are going to set programmatically is accessed on the Users edit profile page as Picture:

Once set this will display the picture on the user profile like this


To do this I need to revisit our User.csv import file and add an extra field that gives the name of the JPG file that holds the users picture.
I’m going to assume that the previous blog post Upload a directory of files in 4 lines has already uploaded the users picture to the SiteCollectionImages picture library, in real life you’d probably use a separate picture library.


Ideally a profile import has occurred after we have added the users to Active Directory and populated the SharePoint profile database.

Now to set the Users Picture property we know to know the Property Name of the Picture Field.
To make this easy to find out here’s the first function for our toolbox Get-SPUserProfileConfigManager.
This function returns a UserProfileConfigManager (http://msdn2.microsoft.com/en-us/library/microsoft.office.server.userprofiles.userprofileconfigmanager.aspx), note this is the new class that resides in the Microsoft.Office.Server namespace not the v2 obsolete one that lives in Microsoft.sharePoint.Portal.UserProfiles.
Also ignore the sample currently given in the MSDN documentation above, it won’t work as it uses the old classes where you pass a PortalContext to the constructor whereas the new version of the classes take a ServerContext object.

 

# Function: Get-UserProfileConfigManager # Description: return a UserProfileConfigManager object which is used for management of MOSS User Profiles # Parameters: PortalURL URL for the Portal Site Collection # # function Get-UserProfileConfigManager([string]$PortalURL) { # Need to get a PortalContext object # as we do not have a HttpContext we need to source one the hard way $site=new-object Microsoft.SharePoint.SPSite($PortalURL) $servercontext=[Microsoft.Office.Server.ServerContext]::GetContext($site) $site.Dispose() # clean up # Return the UserProfileConfigManager new-object Microsoft.Office.Server.UserProfiles.UserProfileConfigmanager($servercontext) }

 

Once we get the UserProfileConfigManager we can call GetProperties and list the internal and display names for each profile property

$cm=get-userprofileconfigmanager "http://sps:2828" $cm.getproperties() | select name, displayname Name DisplayName ---- ----------- UserProfile_GUID Id SID SID ADGuid Active Directory Id AccountName Account name FirstName First name LastName Last name PreferredName Name WorkPhone Work phone Office Office Department Department Title Title Manager Manager AboutMe About me PersonalSpace Personal site PictureURL Picture UserName User name QuickLinks Quick links WebSite Web site PublicSiteRedirect Public site redirect SPS-Dotted-line Dotted-line Manager SPS-Peers Peers SPS-Responsibility Responsibilities SPS-Skills Skills SPS-PastProjects Past projects SPS-Interests Interests SPS-School Schools SPS-SipAddress SIP Address SPS-Birthday Birthday SPS-MySiteUpgrade My Site Upgrade SPS-DontSuggestList Don't Suggest List SPS-ProxyAddresses Proxy addresses SPS-HireDate Hire date SPS-LastColleagueAdded Last Colleague Added SPS-OWAUrl Outlook Web Access URL SPS-ResourceSID Resource Forest SID SPS-ResourceAccountName Resource Forest Account Name SPS-MasterAccountName Master Account Name Assistant Assistant WorkEmail Work e-mail CellPhone Mobile phone Fax Fax HomePhone Home phone

So from this list I see that I need to set the PictureURL property, to get a UserProfile we first need a UserProfileManager object:

# Function: Get-SPProfileManager # Description: Return a UserProfileManager object which is used for accessing MOSS User Profiles # Parameters: PortalURL URL for the Portal Site Collection # function Get-SPProfileManager([string]$PortalURL) { # Need to get a PortalContext object # as we do not have a HttpContext we need to source one the hard way $site=new-object Microsoft.SharePoint.SPSite($PortalURL) $servercontext=[Microsoft.Office.Server.ServerContext]::GetContext($site) $site.Dispose() # clean up # Return the UserProfileManager new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($servercontext) }

And then a helper function Get-SPUserProfile to obtain the UserProfile object itself:

# Function: Get-SPUserProfile # Description: Return a UserProfile object, this will be created if it does not exist # Parameters: PortalURL URL for the Portal Site Collection # DomainUser UserName in Domain\user format function Get-SPUserProfile([string]$PortalURL, [string] $DomainUser) { $upm= Get-SPProfileManager([string]$PortalURL) if ($upm.UserExists($DomainUser) -eq $false) { $upm.CreateUserProfile($DomainUser) } $upm.GetUserProfile($DomainUser) }

Note that this function will create the UserProfile if it does not already exist.

Now we just need a function that makes it easy to set a single UserProfile property, if you have multiple properties to set it would be best to do them all at once and then call commit.

# Function: Set-UserProfileProperty # Description: Sets a property on a User Profile # Parameters: UserName [optional] UserName in Domain\user format # PropertyName Property to set # PropertyValue Property Value to set # $UserProfile UserProfile object, if using this in a loop this should be set # function Set-UserProfileProperty([string]$UserName, [string] $PropertyName, [string] $PropertyValue, [Microsoft.Office.Server.UserProfiles.UserProfile] $UserProfile) { # If we are not passed a UserProfile object then create it # if ($UserProfile -eq $null) { $UserProfile = Get-SPUserProfile($UserName) } $UserProfile[$PropertyName].Value= $PropertyValue $UserProfile.Commit() }

Note this function can either be called with a pre-created userProfile object or a UserName.

Heres the updated Users.CSV with the Picture Field added at the end  

LoginName, DisplayName, FirstName, LastName, Email, Picture brianb, Brian Ballack, Brian, Ballack, brianb@contoso.com, cowner10.jpg walterf, Walter French, Walter, French, walterf@contoso.com, cowner12.jpg

Now a function to tie this all together, it imports the CSV files, locates the user profile by login name and updates the user’s Picture URL:

function Set-UserPictures([string] $PortalURL, [string] $UserFile, [string] $Domain ) { Import-Csv $UserFile | foreach-object { $name=$Domain + "\" + $_.LoginName; $fullURL=$PortalURL + "/" + $_.Picture; Set-UserProfileProperty $PortalURL $name "PictureURL" $fullURL } }

 And you can make use of all of the above code by running this command:

Set-UserPictures "http://sps:2828" "users.csv" "contoso"

Ok now we're all set to add the Contact WebPart to each publishing page in the next post.

Sunday, January 28, 2007 6:24:37 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Thursday, January 25, 2007

Made the UK PowerShell User Group meeting last night in Wokingham, just, the weather and people having accidents on the M3 and M4 kept me late. Got to try out my new Acer GPS unit based on Windows Mobile 5, worked beautifully until setting the return journey when a fatal exception dialog popped up on route calculation, I had to reboot the unit, having seen that dialog many times developing on WM I just had to laugh.

Nice to meet other PowerShell enthusiasts, kudos to PowerGadgets for supplying the beer and pizza and Global Knowledge for hosting.

The meeting was hosted by all round good guy Thomas Lee along with Richard Siddaway. Thomas gave an interesting presentation on PowerShell installation a lot of which I didn't know.

One point to come out of the discussion was the number of profiles that PowerShell will load when it first starts up. Here are the locations and order the profiles get loaded in, note these files won't exist unless you or your admin has created them

  1. %windir%\system32\WindowsPowerShell\v1.0\profile.ps1  (all users, all shells)
  2. %windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1 ( all users, the Windows Powershell shell)
  3. %userprofile%\My Documents\WindowsPowerShell\profile.ps1  (per user, all PowerShell versions)
  4. %userprofile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 ( per user and the default Windows Powershell shell)

Now you can put code or functions in each of these files but the last loaded file wins if there are any conflicts.

This could be a problem with some companies that would like to define a corporate wide profile for every user and put it in system32\WindowsPowerShell\v1.0, as a user I can override any of the company function definitions with my own code in my own profile. You could lock down the PowerShell %userprofile% files but that might cause other problems.

Someone pointed out at the meeting what was needed is a readonly profile that can be loaded globally and last for every user but hey presto there's a PowerShell team blog out today on making functions read-only http://blogs.msdn.com/powershell/archive/2007/01/25/controlling-powershell-function-re-definition.aspx , now that's what I call service.

 

As the meeting closed Thomas also gave out a USB Pen drive to everyone who turned up loaded with PowerShell related goodies, woo hoo free stuff, and oh yeah I'll be speaking at the next meeting about controlling SharePoint with PowerShell, should happen sometime in March.

 

 

Thursday, January 25, 2007 9:36:19 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, December 17, 2006

 

As a follow on from my previous post we can do some neat calculations on the amount of data stored in MOSS personal sites using Powershell.

Using the measure-object CmdLet against the StorageUsedMB property we can calculate the number of personal sites (+1 one as it includes the root site), average size of of each site, smallest, largest and total storage size of all sites.

Again assuming http://sps:20488 is where your personal sites are hosted

PoSH C:\demo> $output=stsadm -o enumsites -url "http://sps:20488"
PoSH C:\demo> $xml=[XML]$output
PoSH C:\demo> $xml.sites.site | measure-object storageusedmb -min -max -sum -average | format-table

Count Average Sum Maximum Minimum Property
----- ------- --- ------- ------- --------
5      0.62   3.1 0.7     0.4     StorageUs...

To get a list of the sites in question with the largest at the top use -descending on the sort CmdLet:

PoSH C:\demo> $xml.sites.site | sort storageusedmb -descending | select url, owner, storageusedMB | format-table

Url                         Owner                    StorageUsedMB
---                         -----                    -------------
http://sps:20488/person... CONTOSO\mike               0.7
http://sps:20488/person... CONTOSO\jeff               0.7
http://sps:20488/person... CONTOSO\administrator      0.7
http://sps:20488           CONTOSO\administrator      0.6
http://sps:20488/person... CONTOSO\brianb             0.4

And if you just want the top 2 offenders us the -first option on the select-object CmdLet

PoSH C:\demo> $xml.sites.site | sort storageusedmb -descending | select url, owner, storageusedMB -first 2 | format-table

Url Owner StorageUsedMB
--- ----- -------------
http://sps:20488/person... CONTOSO\mike 0.7
http://sps:20488/person... CONTOSO\jeff 0.7

 

Obviously in real life those figures would be a lot larger!

Sunday, December 17, 2006 4:58:38 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 

A point came up at the UK SharePoint User Group Chrismas drink, about Personal sites and whether they were top level sites i.e they exist as records in the Sites table and are the top level container for all its subwebs, I hadn’t checked this in v3 so a quick check with PowerShell and stsadm confirms that this is still the case as in V2

Assuming http://sps:20488 is where your personal sites are hosted calling stsadm -o enumsites and processing the returned XML in PowerShell gives us

PoSH C:\demo> $output=stsadm -o enumsites -url "http://sps:20488"
PoSH C:\demo> $xml=[XML]$output
PoSH C:\demo> $xml.sites.site

Url : http://sps:20488
Owner : CONTOSO\administrator
ContentDatabase : WSS_Content_11fba01f-f0c4-4a05-a3c3-868499fd31ce
StorageUsedMB : 0.6
StorageWarningMB : 0
StorageMaxMB : 0

Url : http://sps:20488/personal/administrator
Owner : CONTOSO\administrator
ContentDatabase : WSS_Content_11fba01f-f0c4-4a05-a3c3-868499fd31ce
StorageUsedMB : 0.7
StorageWarningMB : 80
StorageMaxMB : 100
Etc…

Tiding up the output a little

PoSH C:\demo> $xml.sites.site | select url, owner

Url Owner
--- -----
http://sps:20488                           CONTOSO\administrator
http://sps:20488/personal/administrator    CONTOSO\administrator
http://sps:20488/personal/brianb           CONTOSO\brianb
http://sps:20488/personal/jeff             CONTOSO\jeff
http://sps:20488/personal/mike             CONTOSO\mike
….

 

 


Sunday, December 17, 2006 4:40:58 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Sunday, December 03, 2006

Now that I have added some content to our portal I want to approve and publish all pages in each publishing web.

To do this I've created a function that takes an MOSS PublishingPage object and a comment that will be added when we check-in, approve and publish.

 

# Function: Approve-PublishingPage
# Description: Approve a single page in a Publishing Web
# Parameters: publishingPage PublishingPage object
# comment Comment to accompany the check-in/approve/publish
#
function Approve-PublishingPage ([Microsoft.SharePoint.Publishing.PublishingPage]$publishingPage, [string]$comment)
{
" Publishing Page: " + $publishingPage.Name

$listitemfile = $publishingPage.ListItem.File

# Check item if checked out
if ($listitemfile.Level -eq [Microsoft.SharePoint.SPFileLevel]::Checkout)
{
   " Checking in page"
   $listitemfile.CheckIn($comment,[Microsoft.SharePoint.SPCheckInType]::MajorCheckin )
}


# If moderation is being used then handle the approval and publishing
if ($publishingPage.ListItem.ParentList.EnableModeration)
{
   $modInformation = $publishingPage.ListItem.ModerationInformation

   " Moderation Enabled"

   # Check for pending approval
   if($modInformation.Status -eq [Microsoft.SharePoint.SPModerationStatusType]::Pending)
   {
      " Approving"

      $listitemfile.Approve($comment)
   }

   # Publish
   if($modInformation.Status -eq [Microsoft.SharePoint.SPModerationStatusType]::Draft)
   {
   " Publishing"
   $listitemfile.Publish($comment)
   }
}
}

this function will be called from Approve-AllPagesInSPWeb

# Function: Approve-AllPagesInSPWeb
# Description: Loop through all the pages in a Publishing Web and checkin and approve them
# Parameters: web SPWeb object
# comment Comment to accompany the checkin/approve/publish
#
function Approve-AllPagesInSPWeb([Microsoft.SharePoint.SPWeb]$web, [string]$comment)
{

# Check this is a publishing web
if ([Microsoft.SharePoint.Publishing.PublishingWeb]::IsPublishingWeb($web) -eq $true)
{

$pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web);

"Checking $($pubweb.URL)" 

   $pubcollection=$pubweb.GetPublishingPages() 

   for($i=0; $i -lt $pubcollection.count; $i++)
   {
      Approve-PublishingPage $pubcollection[$i] $comment
   }

}

}

Now I'd like to use a foreach look around the GetPublishingPages collection but that's not possible due to lack of Generic support in PowerShell at the moment, so an index loop does the job.

To approve all pages in all webs we can pipe the SPWebs to a foreach loop and pass the SPWeb object to Approve-AllPagesInSPweb

$site = spsite "http://yourmossserver"
$site.allwebs | foreach-object {Approve-AllPagesInSPweb $_ "System Approval"}

Added as a function approveall it produces this output

 

In the next step I'll add a Contact WebPart to every page.

 

 

Sunday, December 03, 2006 9:01:15 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [6]  | 
 Sunday, November 19, 2006

In a previous post I've added content to the publishing pages in the legal and finance divisions and its useful to know what fields are in a list when working with the SharePoint API or say the Query By Content WebPart . Yes you can do using the UI but its a pain.

First get the SPWeb object for our site

$site=spweb "http://sps:2828/divisions/finance"
$web=$site.Openweb()

now show the lists on the site

$web.lists | select title,contenttypes

Title                                   ContentTypes                          
-----                                   ------------                          
Documents                               {Document, Folder}                    
Images                                  {Document, Folder}                    
Master Page Gallery                     {Master Page, Folder}                 
Pages                                   {Page, Article Page, Welcome Page, F...
Workflow History                        {Workflow History}                    
Workflow Tasks                          {Task, Folder}
                        


The Pages list holds the publising pages so let's list its fields


$web.lists["Pages"].Fields | select title, internalname, typedisplayname | sort title

Title                      InternalName               TypeDisplayName         
-----                      ------------               ---------------         
Approval                   Approval                   Workflow Status         
Approval Status            _ModerationStatus          Moderation Status       
Approver Comments          _ModerationComments        Multiple lines of text  
Article Date               ArticleStartDate           Date and Time           
Byline                     ArticleByLine              Single line of text     
Check In Comment           _CheckinComment            Lookup                  
Checked Out To             CheckedOutTitle            Lookup                  
Checked Out To             CheckoutUser               Person or Group         
Checked Out To             LinkCheckedOutTitle        Computed                
Client Limit               Client_x0020_Limit         Number                  
Collect Feedback           CollectF                   Workflow Status         
Collect Signatures         CollectS                   Workflow Status         
Contact                    PublishingContact          Person or Group         
Contact E-Mail Address     PublishingContactEmail     Single line of text     
Contact Name               PublishingContactName      Single line of text     
Contact Picture            PublishingContactPicture   Hyperlink or Picture    
Content Type               ContentType                Choice                  
Content Type ID            ContentTypeId              Content Type Id
       

etc...

There are a lot of fields, to get the count use $web.lists["Pages"].Fields | measure-object
That gives 92 fields for the Pages library.

To see the content publishing pages themselves use

$web.lists["Pages"].Items | select name, file, level

Name                       File                                           Level
----                       ----                                           -----
default.aspx               Pages/default.aspx                             Draft
Client1.aspx               Pages/Client1.aspx                             Published


and finally two functions for our toolbox to make calling these easier

function get-SPListFields([string]$URL, [string]$ListName)
{
$site=get-spweb $URL
$web=$site.OpenWeb()
$list=$web.Lists[$ListName]
$list.Fields
}

function get-SPListItems([string]$URL, [string]$ListName)
{
$site=get-spweb $URL
$web=$site.OpenWeb()
$list=$web.Lists[$ListName]
$list.Items
}

These functions will come in useful later when we approve pages in a site with PowerShell.

 

 

Sunday, November 19, 2006 3:09:58 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 

One of the things that the PowerShell team has always pointed out is the importance of naming conventions in functions.
Most of the bult-in PowerShell functions have a verb-noun format i.e. get-process, get-service etc..
Keeping things consistent across the different types of providers helps with the learning process as you can almost guess what a cmdlet would be called once you know the noun.

Up to now I thought this was just a syntax sugar but this blog entry from the main PowerShell guy Jeffrey Snover points out an important benefit if you name your functions correctly.
When you type a function name, and PowerShell tries to match the correct code to call, it will automagically add a get- to the function name and try to match on that if it fails to find a function of the exact name.

Heres an example take the simple get-SPSite function

function get-SPSite([string]$url)
{
   new-object Microsoft.SharePoint.SPSite($url)
}

I've been using this as $a=get-spsite "http://server" but I could have used $a=spsite "http://server". Its a small thing but if you're typing on the command those extra four characters add up plus it almost looks like C# code not having to use a lengthy namespace prefix.

Likewise for get-SPWeb

function get-SPWeb([string]$url)
{
   $site=new-object Microsoft.SharePoint.SPSite($url)

   $site.OpenWeb()
}

 


 

Sunday, November 19, 2006 3:04:49 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, November 15, 2006

Everyone and their dog will have this link but I'll post it anyway.

Windows PowerShell 1.0 has been released. This page has a list of the download links for XP, Windows Server 2003 and Vista .

http://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx

You might have to be patient as the links were a bit flakey when I tried them.

A point to note is that the Vista version is at RC2 status. Jeffrey Snover explains the Vista release delay here http://blogs.msdn.com/powershell/archive/2006/11/15/windows-powershell-windows-vista.aspx. Checking the comments it seems some people are getting hot under the collar about the delay but as I see it the PowerShell team have done a great job and by all accounts the only difference between RC2 and RTM is the installer. Personally given my bad beta experiences of Vista I'm happier installing the RC2 of PowerShell than the RTM of Vista.

Also worth a download is the Documentation Pack as it contains a Getting Started Guide and a User Guide.

 

 

 

Wednesday, November 15, 2006 9:57:09 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [1]  | 
 Sunday, November 12, 2006

Ok now we have the main structure of our Portal with the new Areas we wanted and we need to start adding some content.

As the Area's we have created are Publishing sites we're going to start using the new Publishing API's in WSS to add content.

The first function to help us with this is called Add-Content. This function takes a Site Collection URL, Area URL, Contents Title, Content Text in HTML format and a check-in comment. This function adds the given text and title to the default content page in the Publishing site.
With a few changes you could modify it to add to a specific content page.

# Function: Add-Content
# Description: Add the given text and title to the default publishing page in the publishing web
# Parameters: SiteCollectionURL URL for the root of the Site Collection
# Area Relative URL to the site/subweb/area
# Title Title string for the page
# Text Content to publish
# Comment Checkin comment
function Add-Content($SiteCollectionURL, $Area, $Title, $Text, $Comment)
{

$url = $SiteCollectionURL + "/" + $Area

write-host "Adding content to " $url

$site = new-object Microsoft.SharePoint.SPSite($url)

$web = $site.OpenWeb()

$pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web)

$pp=$pubweb.DefaultPage

$pp.CheckOut()

# Set the properties
$item=$pp.Item
$item.set_Item("Title",$Title)
$item.set_Item("PublishingPageContent",$Text)
$item.Update()

# Checkin, Approve and Publish
$pp.CheckIn( $Comment )
$pp.Approve( $Comment )
$pp.Publish( $Comment )


}

Note the set_Item syntax, the SharePoint item property seems to conflict with PowerShell's built in properties.
This code assumes Moderation is turned on the Publishing Site.

So we have a handy function to add content but again I want to source that content from an external source.
In this case it's an XML file called content.xml the start of which looks like this:
<contents>
<content>
<area>Divisions/Finance</area>
<title>
Finance Division
</title>
<text>&lt;b&gt;Lorem ipsum dolor sit amet, consectetuer adipiscing elit.&lt;/b&gt;&lt;hr/&gt;&lt;br/&gt; Nullam hendrerit lacinia purus. Proin vulputate porta nisl. Aliquam commodo lobortis lacus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed quis leo imperdiet nisl ultrices fringilla. Praesent enim est, commodo sed, pharetra mattis, condimentum ut, arcu. Morbi aliquet lacus vel elit. In quis nibh. Vestibulum tincidunt. Sed quis sem.
Maecenas lobortis convallis dolor. Nunc rutrum, nunc ac elementum tempor, velit est vehicula libero, eu fermentum lacus lacus ac diam. Curabitur risus quam, dignissim ut, mollis vel, nonummy at, metus. Mauris elit libero, interdum sit amet, sollicitudin nec, eleifend vel, magna. Aliquam at ipsum. Ut rutrum convallis turpis. Quisque urna quam, tincidunt id, pretium a, dignissim ac, neque. Donec ipsum. Sed ornare pretium diam. Phasellus massa. Morbi porttitor purus eget turpis. Sed vel lectus. Etiam egestas nibh vitae augue. Ut felis arcu, fermentum sed, venenatis eget, tincidunt et, lorem. Etiam commodo nisi ut nisl. Morbi augue enim, accumsan eu, dignissim a, scelerisque non, nunc.
Praesent mauris ante, pretium eget, volutpat quis, congue eget, odio.&lt;br/&gt; Praesent sed orci nec sapien molestie viverra. Aenean pulvinar dictum mauris. Quisque ligula est, vestibulum id, consequat vel, ullamcorper id, libero. In tristique. Duis turpis augue, egestas sed, semper eget, dignissim sed, nisl. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Curabitur feugiat dolor cursus lacus. Curabitur dui augue, tempus id, sollicitudin vel, pharetra a, augue. Donec vestibulum dictum ligula. Ut velit dui, dignissim at, interdum quis, convallis a, arcu. Vivamus neque lorem, sollicitudin et, malesuada sed, rhoncus eu, pede. Aliquam hendrerit imperdiet lacus. Duis iaculis fringilla risus. Aliquam pretium ante quis arcu. Nam erat est, porttitor non, venenatis at, auctor sed, libero. Sed condimentum, ante vitae dignissim egestas, dolor nisl rutrum elit, nec ultrices lacus ipsum et pede. Duis dolor turpis, lacinia eu, facilisis ut, fermentum sit amet, nisl. Proin imperdiet mauris a lacus. Nullam suscipit imperdiet tellus.
</text>
........

Its a simple format that has the relative URL of the destination area, the content title and the contents in encoded HTML in its XML nodes. I've encoded the HTML as support for CDATA sections is not as easy as it should be in PowerShell at the moment.

Now I was going to use the import-xml cmdlet that was available in Monad but that seems to have disappeared in recent builds so to import this file I'm going to use the get-content cmdlet, create a variable from it (the $() syntax) and cast it to XML

$xml=[XML]$(get-content Content.xml)

The [XML] is a shorthand way to load the XML into an XMLdocument class
so

$xml | get-member


shows the typename as being the XmlDocument class. If you're used to using this in C# or VB.Net then you have access to the class as normal but the cool thing about PowerShell is the $xml variable now has extra properties that match the nodes in the XML file

$xml.contents.content


will list the content nodes and

$xml.contents.content[0].area


will show Divisions/Finance


The import-content function will do all the hard work.
I'm just piping the list of content nodes into the add-content function and referencing the node name as properties

# Function: import-content
# Description: Use the XMl import file to import some sample content into the Publishing Web
# Parameters: SiteCollectionURL URL for the root of the Site Collection
# ImportFile XML file containing the sample data
function import-content($SiteCollectionUrl,$ImportFile)
{

$xml=[XML]$(get-content $ImportFile)

# Loop through the xml items
$xml.Contents.Content | foreach-object { Add-Content $SiteCollectionUrl $_.Area $_.Title $_.Text }


}


So with a few lines of code this function is loading the contents of the XML file and piping the values of the nodes into our add-content function.

Lets have a look at what the Portal looks like so far


All this and we have not had to use the MOSS UI at all!

Now all those imported content pages will need to be approved. Do it by hand maybe? nope, thats our next PowerShell powered step.

 

 

Sunday, November 12, 2006 7:04:46 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Monday, November 06, 2006

In this step I want to start filling out the Portal with some business areas from a list that has been defined for us

We're going to use a CSV file in the same way as we did for the users. The start of the file looks like this

AreaURL, AreaName, AreaTitle, AreaDescription, AreaTemplate
"Divisions","Divisions","Divisions Home Page", "This area includes links to content based on divisions in the company.", "BLANKINTERNET#2"
"Divisions/Sales","Sales","Sales Home Page", "This area includes information related to sales.", "BLANKINTERNET#2"
"Divisions/Support","Support","Support Home Page", "This area includes information related to support.", "BLANKINTERNET#2"
"Divisions/HumanResources","Human Resources","Human Resources Home Page", "This area includes information related to human resources.", "BLANKINTERNET#2"
"Divisions/Marketing","Marketing","Marketing Home Page", "This area includes information related to marketing.", "BLANKINTERNET#2"


We have a AreaURL column which is the URL relative to the site collection root and we also have the Area Name, Title and description.
The AreaTemplate field in this example is BLANKINTERNET#2 (format is WebTemplate#Configuration).
Now I know this is the Publishing Site template under the Publishing tab but we could just as easily create a team site, subsites of blogs or WIKI's etc.
The easist way to find out what template and configuration to use is to create a site of the type you want through the UI and use powershell to find out what template is used

Run these commands to get a list of the Templates in use on the portal

$sp=new-object microsoft.sharepoint.spsite("http://sps:2828")
$sp.allwebs | select serverrelativeurl, webtemplate, configuration


also checkout Dan Winter's list of the MOSS 2007 templates on his blog http://blogs.msdn.com/dwinter/archive/2006/07/07/659613.aspx


Now to the PowerShell functions
First a simple wrapper to add a new site to the Site Collection: add-spweb

# Function:         add-spweb
# Description:        Create a new Web
# Parameters:        SiteCollectionURL     URL for the root of the Site Collection
#            WebUrl         relative URl of the sub site
#            Title             Title string
#            Description         Description string
#            Template        Template to use
#
function add-spweb([string]$SiteCollectionUrl, [string]$WebUrl, [string]$Title, [string]$Description, [string]$Template)
{


    # Create our SPSite object
    $spsite=new-object Microsoft.SharePoint.SPSite $SiteCollectionUrl

    # Add a site
    $spsite.Allwebs.Add($WebUrl, $Title, $Description ,[int]1033, $Template, $false, $false)
    
    # Note: The new SPWeb will be returned from this call
}

And then a function that will import the CSV file, create a set of objects for each Area line in the CSV file and pipe the list to add-spweb to add a new site.


# Function:         Import-Sites
# Description:        Create a set of subwebs as listed in the import CSV file
# Parameters:        CSVFile         Location of the CSV file containing the list of webs
#            SiteCollectionURL     URL for the root of the Site Collection    
#    
function Import-Sites([string]$CSVFile, [string]$SiteCollectionURL)
{
    Import-Csv $CSVFile | foreach-object { add-spweb $SiteCollectionURL $_.AreaURL $_.AreaName $_.AreaDescription $_.AreaTemplate } | foreach-object {$_.Navigation.UseShared=$true; $_.Update() }
}

I'm also setting UseShared to true which tells the subareas to use the main portal navigation elements.

Use it like this

import-sites "ContosoAreas.CSV" http://sps:2828

The next step will be to import some content into our Publishing Areas...

 

Monday, November 06, 2006 9:32:42 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, November 01, 2006

Ok now we have the users in AD we can add them to the portal. Again we can use import-csv to add them from the users CSV file

heres the routine

# Function:         Add-UsersToSP
# Description:        Add each user in the import CSV file to the given role
# Parameters:        SiteCollectionURL     URL for the root of the Site Collection    
#            UserFile         Location of the CSV file containing the users
#            Domain            Users domain
#            Role             Name of the SharePoint Role e.g Reader, Contribute
#
function Add-UsersToSP([string]$SiteCollectionURL,[string]$UserFile, [string]$Domain, [string]$Role)
{
Import-Csv $UserFile | foreach-object {$spsite=new-object Microsoft.SharePoint.SPSite($SiteCollectionURL) } {$spsite.RootWeb.Roles[$Role].AddUser($Domain + "\" + $_.LoginName, $_.Email, $_.DisplayName, "") }
}

In this script we get a SPSite object, get its rootweb and index into the roles collection to return the role we want. We then use the AddUser method to add the user.

And we call it like this Add-UsersToSP "http://sps:2828" "users.csv" "contoso" "contribute"

Now there is something a little different going on in this script. In the foreach-object loop there are 2 scriptblocks (the curly braces). This is because you can have up to 3 scriptblocks in the foreach clause: Begin, Process and End

The Begin scriptblock will be called once at the start of the iteration, Process is called for each object in the collection and End will be called at yes the end of the iteration allowing you to clean up your objects. I don't have an end in this case but you could call dispose on the SPSite object.

In v3 the Roles collection is deprecated and you should start using the new SPRoleDefinition and SPRoleAssignment classes. These new classes have full support for the new security features but for now I'm keeping things as simple as I can. 

Now is a good time to point out how easy it is to explore the SharePoint OM interactively, in this case the Roles collection.

First of all from the command line do this

PS C:\demo> $spsite=new-object microsoft.sharepoint.spsite("http://sps:2828")
PS C:\demo> $spsite.rootweb.roles

this produces a listing like this

Name : Full Control
Users : {}
Groups : {SUGUK Intranet Owners}
Type : Administrator
Description : Has full control.
Xml : <Role ID="1073741829" Name="Full Control" Description="Has ful
l control."
Type="5" />
ID : 1073741829
PermissionMask : FullMask
ParentWeb : SUGUK Intranet

Name : Design
Users : {}
Groups : {Designers}
Type : WebDesigner
Description : Can view, add, update, delete, approve, and customize.
Xml : <Role ID="1073741828" Name="Design" Description="Can view, add
, update, delete, approve, and customize."
Type="4" />
ID : 1073741828
PermissionMask : 1012866047
ParentWeb : SUGUK Intranet

.....

You can use the select CmdLet to produce a simple table listing

PS C:\demo> $spsite.rootweb.roles | select name, users

Name                                    Users                                 
----                                    -----                                 
Full Control                            {}                                    
Design                                  {}                                    
Manage Hierarchy                   {}                                    
Approve                                {}                                    
Contribute                             {Brian Ballack, Walter French}        
Read                                    {}                                    
Restricted Read                      {}                                    
Limited Access                       {NT AUTHORITY\authenticated users, S...
View Only                              {}  

 

If we want to see the full object of say the RootWeb you can do this

PS C:\demo> $spsite.rootweb | get-member

or just its properties

PS C:\demo> $spsite.rootweb | get-member -membertype property

or just its methods

PS C:\demo> $spsite.rootweb | get-member -membertype methods

I find myself using this lot before coding C# against an object as I can try out the API and mess around with it before running up VS2005

The next step will be to create a host of portal areas as defined in a CSV file.

 

 

 

 

 

Wednesday, November 01, 2006 8:05:34 PM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Tuesday, October 31, 2006

Step 2 in our series is to add some users to Active Directory.

First we need a simple routine to add users to Active Directory

Update 3-11-2006 : The original add-aduser would only work in versions of PowerShell pre RC2. RC2 included some breaking changes to how the DirectoryEntry object handled. I;ve added an RC2 compatible routine.

Pre RC2 version


function add-aduser([string]$LoginName, [string]$DisplayName, [string]$FirstName, [string]$LastName)
{

    $cn=$LoginName
    $sam=$LoginName
    $pw="P@ssword1"


    $ad= new-object System.DirectoryServices.DirectoryEntry
    $u = $ad.get_Children().Find("CN=Users")
    $NewUser = $u.get_Children().add("CN=$cn",'User')

    
    $NewUser.InvokeSet("sAMAccountName",$sam)
    $NewUser.InvokeSet("displayName",$DisplayName)
    $NewUser.InvokeSet("FirstName",$FirstName)
    $NewUser.InvokeSet("LastName",$LastName)
    
    $NewUser.CommitChanges()

    $ad=new-object System.DirectoryServices.DirectoryEntry
    $u = $ad.get_Children().Find("CN=Users")

    $NewUser= $u.get_Children().Find("CN=$cn");
    $NewUser.Invoke("SetPassword",$pw)
    $NewUser.InvokeSet("AccountDisabled",$false)

    # set that the password never expires
    $NewUser.userAccountControl[0] = $NewUser.userAccountControl[0] -bor (65536)

    $NewUser.CommitChanges()

}

 

RC2 Version


function add-aduser([string]$LoginName, [string]$DisplayName, [string]$FirstName, [string]$LastName)

{

   $cn=$LoginName
   $sam=$LoginName
   $pw="P@ssword1"

   # Get an ADSI object for the default domain
   $ad= [ADSI]""

   # Get the Users OU as default
   $ou = $ad.psbase.Children.Find("CN=Users")

   # Add the user
   $NewUser = $ou.psbase.Children.Add("CN=$cn",'User') 

   # Set the basic properties
   $NewUser.Put("sAMAccountName",$sam)
   $NewUser.Put("displayName",$DisplayName)
   $NewUser.Put("givenname",$FirstName)
   $NewUser.Put("sn",$LastName)

   # Commit changes 
   $NewUser.SetInfo() 

   
   # Set our password 
   $NewUser.psbase.Invoke("SetPassword",$pw) 

   # And enable the account
   $NewUser.psbase.InvokeSet("AccountDisabled",$false

   # set that the password never expires
   $NewUser.userAccountControl[0] = $NewUser.userAccountControl[0] -bor (65536) 

   # Commit changes
   $NewUser.SetInfo()


}



This gets us a function we can call to add test users. Note we're hardcoding the OU to users, to make this more production you'd want to parameterize the OU, passwords and set the AccountControl flags to Change Password on next login, there's a lot of other resources out there to help with that.

So If we put that in a script file loaded from our Profile we can call it like this

add-aduser "joeb" "joe blogs" "joe" "blogs"

That's nice but with PowerShell we can do better. We really want to data drive this and the built-in import-csv function will parse a CSV and create a collection of objects that match the CSV schema.

Take a simple User's CSV file like this

LoginName, DisplayName, FirstName, LastName, Email

brianb, Brian Ballack, Brian, Ballack, brianb
walterf, Walter French, Walter, French, walterf


 

Now if we run an import-xml command on the CSV file this is the output

 

Each line has been parsed and an object created. To see this more clearly we can use the get-member command to reflect over the object and see what the object looks like.

 

(Note: it will be PSCustomObject not MshCustomObject in post RC0 builds , I'm running Exchange 2007 on this VPC which requires PowerShell RC0)

As you can see the CSV columns have been added as a NoteProperty property (this is part of the extensible type system).

So now we can create a really simple function to import a CSV file of users, pipe the output to a foreach loop and add each user to Active Directory.

# Function:         Import-Users
# Description:        Create users in active directory as listed in the import CSV file
# Parameters:        UserFile         Location of the CSV file containing the users
#
function Import-Users([string]$UserFile)
{
    Import-Csv $UserFile | foreach-object { add-aduser $_.LoginName $_.DisplayName $_.FirstName $_.LastName }
}

Note that when you receiving a collection of objects in the pipeline in a scriptblock you have to loop over each object. The $_ is a special variable that gives you the current object in the loop which you can use to access properties and methods.

To call we just do

Import-Users Users.CSV

With this power 500 users are as easy as 1 user.

We're not limited to just using CSV files, I've just picked that format as I'm always amazed at the amount of data I get given in Excel spreadsheets and word documents and CSV is the easiest intermediate format to work with. There is also an import-xml command which we will use later to import an XML file containing portal content. As Powershell can call any .Net library the System.Data set of classes could also be used to pull information from databases.

The next entry will be adding our users to SharePoint.

Tuesday, October 31, 2006 9:13:15 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [3]  | 
 Monday, October 30, 2006

Hi,

Just like to thank all those who attended the Presentation last Thursday on controlling SharePoint with PowerShell and Extending the Administration Object model.

I know it was pretty fast paced and technical so I plan to follow it up with a series of blogs entries recapping the steps and scripts in greater detail.

Some of the topics covered were:

   Powershell Basics

   Exchange produces PowerShell samples from the new UI console

   Creating a new SharePoint WebApplication and applying a portal template

   Adding users defined in a CSV file to Active Directory

   Adding those users defined in a CSV file to SharePoint roles

   Adding in webs as defined in a CSV file

   Adding content in an XML file to a Publishing Web

   Uploading a directory of files in 4 lines of Script.

   Creating a custom STSAdm command

   Creating an application to sync User Profile properties back to Active Directory

I've attached the PowerShell scripts and PowerPoint Slides.

I'm not able to post the sample code of the AD Sync application as parts of the code is proprietary but I will post a sample application that does a scheduled backup using exactly the same template.

Presentation-SPPowerShell.zip (46.78 KB)

Colin Byrne

Flexnet Consultants

Monday, October 30, 2006 10:53:00 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [2]  | 

A quickie.

Heres 4 lines of code to upload a whole directory of files, in this case pictures, to a SharePoint document or image library.

The directory pictures contains the images.

The destination is the image library SiteCollectionImages for the portal running on port 2828

$wc = new-object System.Net.WebClient
$wc.Credentials = [System.Net.CredentialCache]::DefaultCredentials
function getdestname($filename){ "http://sps:2828/sitecollectionimages/" + $(split-path -leaf $filename)}
dir "pictures" | % { $uploadname=getdestname $_; $wc.UploadFile($uploadname,"PUT", $_.FullName) }

Have I mentioned PowerShell just rocks?

Monday, October 30, 2006 10:03:35 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 

In this PowerShell and SharePoint series I'd thought I'd spin through, in order of use, the commands used to create the demo Portal site in the SUGUK user group presentation.

First step: Creating a Web Application using the API.

The new SPWebApplicationBuilder object makes this easy. This object creates a Web Application using a default port and the default settings, you can override any settings you like in your script but for simplicity I'm just changing the default timezone.

SPWebApplicationBuilder also creates an AppPool to go along with the new IIS Website which has Network Service as the user. In Beta 2TR that account doesn't have the correct permissions so you need to change it to a local administrator. I tend to dev on a Virtual machine DC so I'd use the domain admin.

So we have three routines

   new-SpWebApplication - Create the IIS Website and SharePoint settings

   set-apidentity   - set the Application Pool credentials

   get-defaulttimezoneid   - returns the Greenwich Meantime TimeZone ID (adjust this one to suit)

We also then need to create the set of webs that will live inside the Web Application, this is done by calling the Add Method on the Sites method of the Web Application passing it various parameters the most important of which is the template ID, in this case SPSPORTAL to give us the default SharePoint Intranet portal look.

The Powershell commands to tie all this together are

$webapp=new-SPWebApplication

set-apIdentity "http://sps:yourportnumber" "contoso\administrator" "password"

#Create Portal Site Collection

$webapp.Sites.Add("/", "SUGUK Intranet","SUGUK Intranet",1033, "SPSPORTAL", "contoso\administrator", "administrator", "administrator@contoso.com")

Here's new-SPWebApplication

# Function:         new-SPWebApplication    
# Description:        Create and return a new SPWebApplication object
#             Use the default values which will create the web site at a random port
# Parameters:        none
#
function new-SPWebApplication()
{

    # Get our local SPFarm object
    $spfarm = [Microsoft.SharePoint.Administration.SPfarm]::Local

    # Use the new SPWebApplicationBuilder
    $appbuilder= new-object Microsoft.SharePoint.Administration.SPWebApplicationBuilder $spfarm

    # Create Web Application with the default settings
    
    $webapplication = $appbuilder.Create()

    # Set the timezone to Greenwich Mean Time
    $timezone=get-defaulttimezoneid
    $webapplication.DefaultTimeZone = $timezone.ID
    $webapplication.Update()

    # Actually queue the application for creation
    $webapplication.Provision()

    # return the SPWebApplication object
    $webapplication

}

 

# Return the Default TimeZone as used for the majority of our sites
#
function get-defaulttimezoneid
{
    [Microsoft.SharePoint.SPregionalSettings]::Globaltimezones | where-object { $_.Description -like "*greenwich*" }
}


 

Now to change the Credentials for the AppPool is also really simple in V3. The SPWebApplication object exposes a ApplicationPool property which you can use to set its credentials

# Function:         set-apidentity    
# Description:        Set the credentials for the application pool for the given Web Application
# Parameters:        Url        Site Collection URL
#            UserName     UserName
#            Password     Password
function set-apidentity([string]$SiteCollectionURL, [string]$UserName, [string]$Password)
{

        
    $webapp=get-spwebapplication $SiteCollectionURL
    
    
    $webapp.ApplicationPool.CurrentIdentityType= [Microsoft.SharePoint.Administration.IdentityType]::SpecificUser
    $webapp.ApplicationPool.UserName= $Username
    $webapp.ApplicationPool.Password= $Password
    
    # Save the settings
    $webapp.ApplicationPool.Update()

    # Roll the settings out via a Admin Job
    $webapp.ApplicationPool.Provision()


}

 

To me this is way easier than using the UI.

 

Monday, October 30, 2006 9:46:17 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 
 Wednesday, October 25, 2006

Hi,

I'm about to start off a new series of entries about using Powershell to control SharePoint.  There's a big gap in the ability to script SharePoint between stsadm commands and custom .net programs and PowerShell fills it nicely.

All my entries from now on will focus on SharePoint version 3.

PowerShell is 'DOS for the .NET generation' (c) :-) and its a fantastic way to both interactively control SharePoint via its Object Model from a command line and to create scripts that can be run in a batch. Its currently at version RC2 and is available from here http://support.microsoft.com/kb/925228
It installs as a windows update package rather than a separate install as it used to in earlier betas, thats a sign of its being a core element of Windows going forward.

Ok lets do some Powershell SharePoint basics.

First although Powershell can call any .net class the assembly must be loaded first.
By default Powershell loads a small list of assemblies, this command will get the list of loaded assemblies:

[System.AppDomain]::CurrentDomain.GetAssemblies()

The syntax for calling a .NET class's static method is for the brackets go around the Class name and the double colon between the class and the static method

The output from that is a little hard to read lets just list the files involved

[AppDomain]::CurrentDomain.GetAssemblies() | foreach-object { split-path $_.Location -leaf } | sort

Here's the list of files the above command gives on my machine

Microsoft.PowerShell.Commands.Management.dll
Microsoft.PowerShell.Commands.Utility.dll
Microsoft.PowerShell.Commands.Utility.resources.dll
Microsoft.PowerShell.ConsoleHost.dll
Microsoft.PowerShell.ConsoleHost.resources.dll
Microsoft.PowerShell.Security.dll
Microsoft.PowerShell.Security.resources.dll
mscorlib.dll
System.Configuration.Install.dll
System.Data.dll
System.DirectoryServices.dll
System.dll
System.Management.Automation.dll
System.Management.Automation.resources.dll
System.Management.dll
System.ServiceProcess.dll
System.Xml.dll

As you can see SharePoint is not one of those in the list, also missing that could be useful is the System.Web assembly

There are a few ways to load an assembly onto your AppDomain but the easiest is to call the static method LoadWithPartialName on the Assembly class.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

LoadWithPartialName is great because you dont need to specify the full name to the assembly which in SharePoint v3 would be

[System.Reflection.Assembly]::Load("Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

and for MOSS

[System.Reflection.Assembly]::Load("Microsoft.SharePoint.Portal, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")

Now a lot of people will cry LoadWithPartialName has been deprecated as MS have got concerned how it has to make to many guesses over locating the assembly.
Personally I want to see a method that will simply load the latest version of the assembly I've told it to load, in a controlled environment like a SharePoint server thats exactly the behaviour I want to see. <rant> MS for god's sake just document the method properly and let devs choose whether to use it or not. </rant>

Anyway if you want to use the Load method take a look at this blog entry: http://www.leeholmes.com/blog/HowDoIEasilyLoadAssembliesWhenLoadWithPartialNameHasBeenDeprecated.aspx

Now you don't want to type the load commands each time so put them in your Powershell Profile script.
This changes location a lot depending on which version of Powershell your running so see this entry for the full details http://www.leeholmes.com/blog/TheStoryBehindTheNamingAndLocationOfPowerShellProfiles.aspx

So now what can we do with this?

Well first lets get a site collection we can play with

First create an SPSite object and pass it a valid site url


      $spsite= Microsoft.SharePoint.SPSite("http://portal.contoso.com")

to see the contents of the object just type the object on the command line

$spsite

To just get a list of the methods on the SPSite object

   $spsite | get-member -membertype method

To just get a list of the properties on the SPSite object

   $spsite | get-member -membertype property

To get a list of all sub sites

   $spsite.AllWebs

Get a list of webs ordered by the last time that the contents have been changed

   $spsite.allwebs | select LastItemModifiedDate, URL , Created | sort LastItemModifiedDate

There's lots more that you can do and I'll post them as I go.

 

Wednesday, October 25, 2006 10:01:53 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  | 

Whoa, its been a while since I've blogged but sundry projects and SharePoint v3 has taken up all my time.

Just to let you know that I'm presenting at the UK SharePoint users group meeting this Thursday the 26th October.

I'm doing 2 sessions; one on using Powershell with SharePoint v3 in which I'll go through Powershell basics and how to use it to control SharePoint. Then I will attempt to build a portal without touching any settings in the UI! Wish me luck.

The second one will explore the new extensible admin object model.
This will demonstrate creating custom stsadm commands along with creating an application that syncs changed MOSS User profile information back to Active Directory.
It will be a small application integrated into SharePoint and built using the new SPService, SPServiceInstance and SPJobDefinition classes.
I'll be describing how they work together, its cool stuff.

Everybody is welcome (you just need to register on the suguk site) so if you are in London this Thursday it would be great to see you.  The meeting kicks off at 6.30pm

If you plan to attend just register on the SUGUK site and leave your name on this list
http://suguk.org/forums/thread/1490.aspx

cheers,
Colin

Wednesday, October 25, 2006 8:37:47 AM (GMT Standard Time, UTC+00:00)  #    Disclaimer  |  Comments [0]  |