Archive

Posts Tagged ‘Sharepoint’

Australian & New Zealand SharePoint Conference

June 17th, 2010 Niklas Goude 1 comment

I just finished my Australian/New Zealand SharePoint & PowerShell tour with Mattias Karlsson where we had the honor to speak at both the New Zealand and the Australian SharePoint conference. In our session SharePoint 2010 and PowerShell – In real life we showed a couple of demos and promised to share them on this site. So here they are.

Click here to download the scripts

Click here to download the PowerPoint presentation

Rating 3.00 out of 5
[?]

MOSS 2007 Script Collection

September 8th, 2009 Niklas Goude 10 comments

I’ve been working with SharePoint and PowerShell for quite some time now and I would like to share a couple of Scripts that I use when scripting MOSS. Actually, it’s 44 Scripts, Loads of Coffee and alot of long nights :) so I hope you enjoy them. There are Links at the bottom of the Post where you can Download all the scripts, or you can Download all scripts from the link below.

moss-script-collection.zip

Down to business then. I’ll put up a scenario based on the Session that I used at the SharePoint UserGroup meeting in Stockholm Sweden, explaining all Steps and how to use the Scripts.

First I set up a Folder where I keep all my scripts, I use C:\Scripts. Then I add the folder to the Windows Path.


PS > $env:path = $env:path + ";c:\scripts"

 

Adding the Script folder to the Environment Path let’s Us Call the script simply by typing it’s name. so instead of typing:


PS > .\Get-SPSite.ps1 -url http://moss

 

We can Type:


PS > Get-SPSite -url http://moss

 

Note, Don’t forget to set the Execution-Policy, otherwise, the scripts won’t run. Read more about it here


PS > Set-ExecutionPolicy RemoteSigned

 

All Scripts include a help text that explains how to use the Script. To access the helptext simply type the Script Name followed by -help.


PS > Get-SPSite -help

 

Now We can start Scripting MOSS!

Loading SharePoint Assemblies

 

The first thing we have to do in order to Access the MOSS 2007 Assemblies is Loading them into PowerShell. Even though they Exist in our Windows Environment, PowerShell isn’t aware of them. By Loading them into our Global Assembly Cache, PowerShell can access and use the MOSS 2007 .NET Classes.


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

 

Get-SPSite.ps1

 

First, We’ll Check out the Site Collection. Here’s how we can add our Site Collection to a variable using the Get-SPSite.ps1 script and retrieve information from it. When working with SPSite or OpenWeb objects in the PowerShell console you have to dispose of the object on the same row as the command, otherwise they will leak memory. This only applies when you create SharePoint objects directly in the PowerShell console. When run in functions and scripts, the commands are run in a single thread. for more information click here


PS > $SPSite = Get-SPSite -url http://moss; $SPSite | Select Url, Port, Owner | Format-List; $SPSite.Dispose()

Url   : http://moss
Port  : 80
Owner : POWERSHELL\administrator

 
We can also get usage Information:


PS >  $SPSite = Get-SPSite -url http://moss; $SPSite.Usage; $SPSite.Dispose()


Storage           : 550113
Bandwidth         : 0
Visits            : 0
Hits              : 0
DiscussionStorage : 0

 

And even information from the WebApplication Pool 


PS > $SPSite = Get-SPSite -url http://moss; $SPSite.WebApplication.ApplicationPool | Select DisplayName, Status | Format-List; $SPSite.Dispose()


DisplayName : SharePoint - 80
Status      : Online

 

Try Pipe:ing the $SPSite object to Get-Mameber and check out all Available methods and properties available. 


PS > $SPSite = Get-SPSite -url http://moss; $SPSite | Get-Member; $SPSite.Dispose()

 

Get-SPWeb.ps1

 

The Get-SPWeb.ps1 Returns a Site instead of a Site Collection through the OpenWeb() method. Through it, we can modify the Title and description of a site, we can add Items, documents and lots more. Here’s an example on how you can change the Title and Descrition of a Site. 


PS > $OpenWeb = Get-SPWeb http://moss; $OpenWeb.Title; $OpenWeb.Dispose()

Home

PS > $OpenWeb = Get-SPWeb http://moss; $OpenWeb.Description; $OpenWeb.Dispose()

Home

PS >  $OpenWeb = Get-SPWeb http://moss; $OpenWeb.Title = "PowerShell Home"; $OpenWeb.Description = "Demo From PowerShell.nu"; $OpenWeb.Update(); $OpenWeb.Dispose()

 

Here’s What happened to my MOSS RootWeb Site after running these simple commands. 

moss01 

Get-SPList.ps1

 

We’ve accessed The Site Collection and a MOSS Site, Let’s look at how to access a List within a Site. We can do this through the Get-SPList.ps1 Script. We can use it to Get or Set List Information and even Get or Set Items and Fields in the List. 


PS > $SPList = Get-SPList -url http://moss -List Announcements; $SPList.ItemCount; $SPList.Dispose()

3

PS > $SPList = Get-SPList -url http://moss -List Announcements; $SPList.Items | ForEach { $_["Title"] }; $SPList.Dispose()

Get Started with Windows SharePoint Services!
Announcement Added through PowerShell
Demo from PowerShell.nu

 

Get-SPField.ps1

 

A List Contains Field which tell us what kind of information we can add to our Items. When Accessing a Field you can use the Get-SPField.ps1 script. The Field holds alot of information such as Type. 


PS > $Field = Get-SPField -url http://moss -List Announcements -Field Expires
PS > $Field.Type

DateTime

 

You can even edit information in the Field. Here’s an Example on How to Hide the Field in Edit Form. When a User Tries to Edit an item in the Announcements List, he won’t see the Expires Field. 


PS > $Field.ShowInEditForm = $False
PS > $Field.Update()

 

Get-SPView.ps1

 

A List Contains a Variaty of Views. Here’s how you Access a List View in MOSS 2007 using the Get-SPView.ps1 Script. 


PS > $View = Get-SPView -url http://moss -List "Shared Documents" -View "All Documents"

 

The View contains alot of Methods and Properties. Let’s take a look at the Clone() Method. 


PS > [void]$View.Clone("My Cloned View",100,$True,$False)

 

With this Simple Command, I’ve Created a new View Called “My Cloned View”. It’s basically a Copy of the “All Documents” View. 

Get-SPItem.ps1

 

When Accessing Items within a List, you can use the Get-SPItem.ps1 Script. Storing the Item in a Variable Allows us to Get And Modify it’s properties. The script includes an -All Switch that retrieves All Items in a List instead of just one item. 


PS > $Item = Get-SPItem  -url http://moss -List Announcements -Item "Get Started with Windows SharePoint Services!"

 

Now That we have an Item stored in the $Item Variable, we can Modify it. 


PS > $Item["Body"]

Microsoft Windows SharePoint Services helps you to be more eff ective by connecting people, information, and documents. For information on getting started, see Help.
PS > $Item["Body"] = "New Text in Body" PS > $Item.Update()

 

Another Nice Trick is Looping through all Items. First let’s Store them in a variable: 


PS > $AllItems = Get-SPItem -url http://moss -List Announcements -All

Now Let’s Set the Body on All Announcements in the Announcements List.


PS > $AllItems | ForEach { $_["Body"] = "New Text"; $_.Update() }

 

Add-SPAnnouncement.ps1

 

Next, let’s add an Announcement to our RootWeb Site. Using the Add-SPAnnouncement.ps1 sript, we can add through a One-Liner in PowerShell. 


PS > Add-SPAnnouncement -url http://moss -List "Announcements" -Title "Demo from PowerShell.nu" -Body "<h1>PowerShell</h1><p />is Cool!" -Expires (Get-Date).AddHours(1)

 

moss02 

Let’s say that you have multiple sites in your Site Collection and you want to add an Announcement on each site. This can be solved with a Simple ForEach: 


PS > $Sites = "http://moss/HR","http:moss/IT","http://moss/Production","http://moss/Sales"
PS > $Sites | ForEach {
>> Add-SPAnnouncement -url $_ -List "Announcements" -Title "Demo från PowerShell.nu" -Body "

is Coolt!" -Expires (Get-Date).AddHours(1)

 

This Code adds an announcement on each site in the $Sites Array. 

Add-SPCalendar.ps1

 

The Add-SPCalendar.ps1 script adds new Calendar Entries to a MOSS Calendar List. 


PS > Add-SPCalendar -url http://moss -List "Calendar" -Title "SharePoint - PowerShell Demo" -Location "Stockholm" -Description "PowerShell Demo" -StartTime (Get-Date) -EndTime (Get-Date).AddHours(4)

 

The -StartTime and -EndTime Parameters accept an [DateTime] object, which means that we can use the Get-date CmdLet to Add Dates. 

moss03 

Add-SPLink.ps1

 

Here’s a Script that adds Links to a MOSS Links List. It sets the Link, the Description of the Link and the Notes Field. 


PS > Add-SPLink -url http://moss -List "Links" -Link "http://www.powershell.nu" -Description "PowerShell.nu - Blog" -Notes "PowerShell Blog"

 

Here’s what our Newly created Link Item looks like: 

moss04 

Set-SPImageWebPart.ps1

 

On a Default installed MOSS, The Root Web uses the “Team Site” Template, which has an Image WebPart on the Right Displaying a SharePoint Services Image. Let’ go ahead and change the image using the Set-SPImageWebPart.ps1 Script. 


PS > Set-SPImageWebPart -url http://moss -WebPart "Site Image" -Image "C:\Demo\Files\PowerShell.jpg"

 

As you can see in the Image below, Our RootWeb Team Site looks a little PowerShelled. 

moss05 

Set-SPTheme.ps1

Now that we’ve customized our Site with a New “Site Image”, let’s go ahead and change the Theme. We’ll use the Set-SPTheme.ps1 script to achieve this.


PS > Set-SPTheme -Url http://moss -Theme obsidian

 

And with a simple One-Liner, we’ve changed the Theme on our Site. Doing without the script takes about two lines of code, but i Added the script since I think it’s pretty cool. 

moss06 

Upload-SPDocument.ps1

 

This Script lets you Upload Documents to a Document Library in MOSS. Here’s how it Works: 


PS > Upload-SPDocument -url http://moss -Folder "Shared Documents" -Document "C:\Documents\Excel SpreadSheet.xlsx"

 

If we look in our “Shared Documents” List, We can see that the Document is uploaded there now. 

moss07 

But What it we want to Upload one hundred documents ? Well, since we are using PowerShell, we can do it with a One-Liner. 


PS > gci C:\Documents | ForEach { Upload-SPDocument -url http://moss -Folder "Shared Documents" -Document $_.FullName }

 

This really shows the Power of Microsoft PowerShell 

Add-SPFolder.ps1

 

Now That we’ve Uploaded a couple of Files, Let’s Add a New Folder to our “Shared Documents”. We can do this by using the Add-SPFolder.ps1 script. 


PS > Add-SPFolder -Url http://moss -List "Shared Documents" -Name "New Folder"

 

If we want to Upload Documents Directly to our Folder we can use the Upload-SPDocument.ps1 Script again, we just point it to our New Folder. 


PS > Upload-SPDocument -url http://moss -Folder "Shared Documents/New Folder" -Document "C:\Documents\Excel SpreadSheet.xlsx"

 

Add-SPTextField.ps1

 

Let’s add a couple of Fields to our “Shared Documents” List. First, we’ll add a Document Owner Field. In this example we’ll use a simple Text field, but you could obviously use a User field instead. We’ll get back to the User field a little later in this post. 


PS > Add-SPTextField -url http://moss -List "Shared Documents" -Name "Document Owner" -Description "Document Owner"

 

This Adds a TextField to our List named “Document Owner”, if you want the field to Require information, simply add -Required to the command above. 

moss08 

Add-SPChoiceField.ps1

 

Next, We’ll add a Choice Field to our “Shared Document”. This can be done by using the Add-SPChoiceField.ps1 Script. Again, if you want the Field to Require information, just add -Required to the command. 


PS > Add-SPChoiceField -url http://moss -List "Shared Documents" -Name "Document Type" -Description "Type of Document" -Choices $("Excel","Word","PowerPoint")

 

Note the -Choices Paramteter. It takes an Array of arguments and Sets each argument as a Choice in the Field. Typing $(“Argument1″,”Argument2″) is a quick way to create an array and passing it as an argument to the script. 

moss09 

Add-SPFieldToView.ps1

 

Now that we have two new Fields in our “Shared Documents”, let’s add them to the “All Documents” View by using the Add-SPFieldToView.ps1 Script. 


PS > Add-SPFieldToView -url http://moss -List "Shared Documents" -Field "Document Owner" -View "All Documents"
PS > Add-SPFieldToView -url http://moss -List "Shared Documents" -Field "Document Type" -View "All Documents"

 

If we check out our “Shared Documents” list now, we can see that the Fields are Added to the “All Documents” View. You can, of course, use this on any type of List in MOSS 2007. 

moss10 

Set-SPItem.ps1

 

Here’s a Really Useful script when working with Items. The Set-SPItem.ps1 Script can either Create a New Item or Modify an existing Item. At first, Let’s take a look on how to Modify existing Items. By Default, the -field param is set to Title, but by changing it to Name, the script will check for a match in the Name Field and if it finds a match, it will update the Item, if it doesn’t find a match it will create a New Item. Note that when Creating Items in a Document Library you have to use the Upload-SPDocument.ps1 script. 

Note that the -Values takes a HashTable Array of Values to Set on the Item. Let’s say a List has Two Fields. A Title field and a Description Field. If I want to Create a New Item Called “New Item” and with The Description “My New Item Description” I could Simply type: 


PS > Set-SPItem -url http://moss -List "My List" -Name "New Item" -Values @{"Description" = "My New Item Description"}

 

If i Want to Edit the Item that i Created i Could reuse the Same Command, since it First looks for an Item Where the Title is Set to “New Item” 

Let’s say i Don’t know the Title of the Item but i Do know It’s Description. By using the -Field paramter i Could get the Correct Item and Modify it. 


PS > Set-SPItem -url http://moss -List "My List" -Name "My New Item Description" -Field Description -Values @{"Title" = "New Title"; "Description" = "Changed Title and Changed Description of Item"}

 

Let’s Take a Look at the Documents that we Added earlier. Here’s an example on adding MetaData on Documents in a Document Library:


PS > Set-SPItem -url http://moss -List "Shared Documents" -Name "Excel SpreadSheet.xlsx" -Field "Name" -Values @{"Document Type" = "Excel"; "Document Owner" = "Niklas Goude"}
PS > Set-SPItem -url http://moss -List "Shared Documents" -Name "Word Document.docx" -Field "Name" -Values @{"Document Type" = "Word"; "Document Owner" = "Niklas Goude"}
PS > Set-SPItem -url http://moss -List "Shared Documents" -Name "PowerPoint Presentation.pptx" -Field "Name" -Values @{"Document Type" = "PowerPoint"; "Document Owner" = "Niklas Goude"}

 

With these Commands I added information in the “Document Type” Field and the “Document Owner” Field on my three Documents, as the image below show. 

moss11 

Let’s Use this Script to Modify the Announcement That we Added Earlier. We’ll Change the Body of the Announcement. 


PS > Set-SPItem -url http://moss -List Announcements -Name "Demo from PowerShell.nu" -Values @{"Body" = "<h2>Modified With Set-SPItem.ps1</h2>"}

 

Here’s what the Announcemet looks like now: 

moss12 

Add-SPList.ps1

 

Now Let’s create our own Custom List. We’ll use the Add-SPList.ps1 Script to do this. Specifying the Type to “Custom List” tells the script to create a “Custom List”. You can, of course create any type of list available in MOSS through this script. 


PS > Add-SPList -url http://moss -Name "My List" -Description "My Custom Demo List" -Type "Custom List"

 

This Creates the List, but it doesn’t Add the List to the QuickLaunch Bar. Let’s check out how to Add a List to the QuickLaunchBar. 

Add-SPListToQuickLaunch.ps1

 

This Script adds lists to the Quicklaunch Bar in MOSS 2007. The Command below shows how you can use the script. 


PS > Add-SPListToQuickLaunch -url http://moss -List "My List"

 

This command adds the List to the QuickLaunch Bar. 

moss13 

Set-SPQuickLaunchOrder.ps1

 

Let’s Change the QuickLaunch Order. We’ll use the Set-SPQuickLaunchOrder.ps1 Script that moves a List to the Top of the QuickLaunch. 


PS > Set-SPQuickLaunchOrder -url http://moss -List "My List"

 

If we look at our site now, We can see that our QuickLaunch Order has been Changed. The “My List” List is now on top. 

moss14 

Now That we have a Custom List, Let’s Add a couple of different Fields, We’ll also add them to the “All Items” View with the Add-SPFieldToView.ps1 script. 

Add-SPCurrencyField.ps1

 

You can Add a Currency Field by using the Add-SPCurrencyField.ps1 Script. 


PS > Add-SPCurrencyField -url http://moss -List "My List" -Name Cash -Description "How much Money do you have?"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field Cash -View "All Items"

 

Add-SPDateTimeField.ps1

 

Here’s how we can add a DateTime Field to a List using the Add-SPDateTimeField.ps1 Script. 


PS > Add-SPDateTimeField -url http://moss -List "My List" -Name "Birthday" -Description "When is Your Birthday?"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field Birthday -View "All Items"

 

Add-SPNoteField.ps1

 

The Note Field Accepts Text on Multiple Rows. Here we add a Note Field using the Add-SPNoteField.ps1 Script. 


PS > Add-SPNoteField -url http://moss -List "My List" -Name Description -Description "About Me.."
PS > Add-SPFieldToView -url http://moss -List "My List" -Field Description -View "All Items"

 

Add-SPNumberField.ps1

 

We can also Add Numeric Fields to MOSS. This example shows how to do that using the Add-SPNumberField.ps1 Script. 


PS > Add-SPNumberField -url http://moss -List "My List" -Name Age -Description "How Old Are You?"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field Age -View "All Items"

 

Add-SPYesNoField.ps1

 

With the Add-SPYesNoField.ps1 script, We can add a Yes/No Checkbox Field to our List. 


PS > Add-SPYesNoField -url http://moss -List "My List" -Name "Windows 7" -Description "Do You Have Windows 7 Installed?"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field "Windows 7" -View "All Items"

 

Add-SPUserField.ps1

 

Adding User Fields that point to a Active-Directory User, Can be Added through the Add-SPUserField.ps1 Script. 


PS > Add-SPUserField -url http://moss -List "My List" -Name User -Description "User"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field User -View "All Items"

 

Add-SPMultipleUserField.ps1

 

A User Field can Allow Multiple Selections. Here’s how to add a multiple User Field using the Add-SPMultipleUserField.ps1 script. 


PS > Add-SPMultipleUserField -url http://moss -List "My List" -Name "Multiple Users" -Description "Multiple Users"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field "Multiple Users" -View "All Items"

 

Add-SPMultiChoiceField.ps1

 

Choice Fields can also accept Multiple Choices. Here’s an example on how to add a Multiple Choice Field using the Add-SPMultiChoiceField.ps1 Script. 


PS > Add-SPMultiChoiceField -url http://moss -List "My List" -Name "Favorite Music" -Description "Favorite Music" -Choices $("Country","Metal","Rock","Soul","Jazz")
PS > Add-SPFieldToView -url http://moss -List "My List" -Field "Favorite Music" -View "All Items"

 

Add-SPLookupField.ps1

The Lookup Field Points to an Item in another List. In this Example we’ll Point it to the “Tasks” List.


PS > Add-SPLookupField -url http://moss -List "My List" -Name "My Tasks" -Description "My Tasks" -LookupList Tasks
PS > Add-SPFieldToView -url http://moss -List "My List" -Field "My Tasks" -View "All Items"

 

Add-SPMultiLookupField.ps1

 

LookupFields Can also have multiple Values. We can add a Multiple LookupList through the Add-SPMultiLookupField.ps1 Script. Again, We’ll Use the Tasks List as Lookup. 


PS > Add-SPMultiLookupField -url http://moss -List "My List" -Name "Multiple Tasks" -Description "Multiple Tasks" -LookupList Tasks
PS > Add-SPFieldToView -url http://moss -List "My List" -Field "Multiple Tasks" -View "All Items"

 

Add-SPURLField.ps1

 

Finally, Let’s Add an URL Field to our “Custom List”. 


PS > Add-SPURLField -url http://moss -List "My List" -Name HomePage -Description "HomePage"
PS > Add-SPFieldToView -url http://moss -List "My List" -Field HomePage -View "All Items"

 

Now, Let’s see what our List Looks like. 

moss15 

Let’s Add Two Task Items and then create a New Item in our “Custom List” using the Set-SPItem.ps1 Script. 


PS > Set-SPItem -url http://moss -List Tasks -Name "My First Task" -Values @{"Priority" = "(3) Low"; "Status" = "In Progress"; "% Complete" = "0.4"; "Assigned To" = "powershell\Administrator"; "Description" = "My First Task"; "Start Date" = "09/07/09"; "Due Date" = "09/08/09"}
PS > Set-SPItem -url http://moss -List Tasks -Name "My Second Task" -Values @{"Priority" = "(1) High"; "Status" = "Not Started"; "% Complete" = "0"; "Assigned To" = "powershell\Administrator"; "Description" = "My Second Task"; "Start Date" = "09/07/09"; "Due Date" = "09/08/09"}

 

Here’s our New Tasks up and running. 

moss16 

Now Let’s Add a New Item in our “Custom List”. Note that Fields that Allow multiple Values are divided by a ; in the command below. For Instance, if I want to two values to a multiple Choice Field I would have to Type: @{“MultiChoiceField” = “Value1; Value2; Value3″}.


PS > Set-SPItem -url http://moss -List "My List" -Name "My First Item" -Values @{"Cash" = "10"; "Birthday" = "05/05/1982"; "Description" = "My First Entry"; "Age" = "27"; "Windows 7" = "Yes"; "User" = "powershell\administrator"; "Multiple Users" = "powershell\administrator; powershell\nigo"; "Favorite Music" = "Metal; Country"; "My Tasks" = "My First Task"; "Multiple Tasks" = "My First Task; My Second Task"; "HomePage" = "http://www.powershell.nu; My Blog" }

 

And Here’s what our Item Looks like in MOSS 2007. 

moss17 

Set-SPView.ps1

Let’s Modify the Apperance of the “All Tasks” View in the Tasks List so that it Groups By Status. When Modifying appearance of a View, We change the View Query. This can be Done by using the Set-SPView.ps1 Script.


PS > Set-SPView -url http://moss -List Tasks -View "All Tasks" -Query ''

 

Here’s what our Tasks Look like now. 

moss18 

Remember the “Shared Documents that We Added Fields to earlier ? Let’s Group the “All Documents” View by one of our New Fields. Note that the Name=”Document_x0020_Type” in the Query. It’s because the Field has Spaces in its Name. 


PS > Set-SPView -url http://moss -List "Shared Documents" -View "All Documents" -Query ''

 

And now our Documents are Grouped by “Document Type”. 

moss19 

Add-SPSpite.ps1

 

With the Add-SPSite.ps1 Script, we can add New Sites to our Site Collection. There are a Couple of Different Templates that we can use. To get a list of all templates available, SImply type the following commands. 


PS > $OpenWeb = Get-SPWeb http://moss; $OpenWeb.GetAvailableWebTemplates(1033) | Select Name; $OpenWeb.Dispose()

 

Let’s Create a New Site For our IT Department. 


PS > Add-SPSite -url http://moss -weburl "IT" -Title "Information Technology" -Description "IT Department" -Template "STS#1"

 

Here’s What the Site looks like now. 

moss20 

Since we used a STS#0 Template, the Site doesn’t contain any Lists or information. 

Add-SPGroup.ps1

 

If we want to Add a New Group to our Site Collection we can use the Add-SPGroup.ps1 Script. Here’s an example on using the Script. 


PS > Add-SPGroup -url http://moss -Group "New Group" -Role Read -Owner "powershell\administrator"

 

Now our “New Group” is Added to our Site with “Read” Permissions 

moss21 

Add-SPUser.ps1

 

With our New Group set up, we can go ahead and add users to it. To accomplish this, we can use the Add-SPUser.ps1 Script. Here’s an example on adding a User to the “New Group”.


PS > Add-SPUser -url http://moss -Group "New Group" -Domain "powershell.nu" -sAMAccountName "goude" -mail "niklas.goude@zipper.se" -FullName "Niklas Goude"

 

If we look in the Group now, our User will be added. 

moss22 

Add-SPSitePermission.ps1

 

Let’s Give our Group Full Permissions on The IT Site that we created earlier.


PS > Add-SPSitePermission -url "http://moss/IT" -Group "New Group" -Permission "FullMask"

 

Now all users in the Group have Full Permissions on the “IT” Site. On the RootWeb, they still have Read Permissions. 

Add-SPImageWebPart.ps1

 

Let’s Add a New Image WebPart to the IT Site that we just created. Here’s an example on how to do it using the Add-SPImageWebPart.ps1 Script.


PS > Add-SPImageWebPart -url http://moss/IT -Name "My Image" -Image "C:\Images\PowerShell.jpg" -ChromeType "None"

 

Now the Image WebPart is Added to the Site. There are a couple of parameters you can use with this script. simply type Add-SPImageWebPart -help to check out available parameters. 


PS > Add-SPImageWebPart -help

 

moss23 

Add-SPListViewWebPart.ps1

 

The Add-SPListViewWebPart.ps1 let’s us Add list View WebParts to our Sites. The Script contains a couple of parameters that let’s you choose Chrome Type, Zone and a couple of other things. Here’s an example on Using the Script.


PS > Add-SPListViewWebPart -url http://moss -List "My List" -Name "Client Statistics" -ChromeType "None"

 

Here’s our New List WebPart in Action! 

moss24 

Remove-SPField.ps1

 

If you want to Remove a Field From a List you can use the Remove-SPField.ps1 Script. Here’s an example on how to use the Script.


PS > Remove-SPField -url http://moss -List "Shared Documents" -Field "Document Type"

 

Remove-SPItem.ps1

 

If you want to Remove a List Item you can use the Remove-SPItem.ps1 script. The -name parameter matches with the Title field by default. If you want to match the name with another field, simply use the -field parameter.


PS > Remove-SPItem -url http://moss -List Tasks -name "My First Task"
PS > Remove-SPItem -url http://moss -List Tasks -name "Not Started" -Field Status

 

Remove-SPList.ps1

 

If you want to Remove an entire List you can use the Remove-SPList.ps1 script,


PS > Remove-SPList -url http://moss -List Tasks

 

This Command Removed the Tasks List from the RootWeb Site. 

Remove-SPSite.ps1

 

When Removing a Site from MOSS 2007 You can use the Remove-SPSite.ps1 script. This exmaple shows how to remove the IT Site that we created earlier.


PS > Remove-SPSite -url http://moss/IT

 

Export-SPSite.ps1

 

Let’s take a Backup of our Site Collection. We can either do this through Central Administration, through an STSADM Command or by Using PowerShell. This Example shows how to use a PowerShell Script to take a Backup of a Site Collection.


PS > Export-SPSite -url http://moss -file Backup.bak -Location C:\Backup\

 

The Command Places a Backup file in C:\Backup\Backup.bak. to automate this you could set up a Scheduled Task that takes a backup at specified weekdays. 

Import-SPSite.ps1

 

Now That we have a Backup, Let’s restore our Site Collection from the Backup file. To achieve this, we can use the Import-SPSite.ps1 Script. Here’s an example on how to use the script.


PS > Import-SPSite -url http://moss -file Backup.bak -Location C:\Backup\

 

Here’s a List of All scripts from this Post. Enjoy! 

Regards

Goude 

 

Rating 3.00 out of 5
[?]
Categories: MOSS, Sharepoint Tags: ,

SharePoint and PowerShell – In real life

March 15th, 2009 Niklas Goude No comments

I’ve had PowerShell.nu for quite some time now, gathering information and writing posts on various ways of solving issues through PowerShell, tips and trix and How too’s that have been both fun and educational for me and hopefully for the people reading my blog.

I think it’s a journey worth taking, not just for the fun of writing but for the people I get to meet and the experiences that we can share through blogs, forums and communities.

One person I’ve met and shared ideas with is Mattias Karlsson. We work at the same company and we share a passion for SharePoint. Mattias is one of the best administrators i know and he’s amazing when it comes to SharePoint. We started of with an idea of sharing our SharePoint experience through cross-blogging, letting people around the world take part of our ideas and help us expand our knowledge through communities, meetings and comments.

Our idea grew to realization and today, we are writing a book on the subject. A large portion of the book will evolve around hands on scenarios and examples that IT administrators will feel familiar with.

We are currently in the beginning of the process so we can’t communicate a deadline yet. We have however set up a website where you can register your email address to get news and updates regarding the Book. This site will also act as our communication point which will develop along the way as our writing is progressing.

We are both really exited about our new project and will of course keep you posted on our blogs, so drop by now and then and send a mail if you have any tips or recommendations in our progress.

SharePoint and PowerShell – In real life

Mattias Karlsson

Rating 3.00 out of 5
[?]
Categories: Book, Sharepoint Tags: ,

Create site with approval workflow using PowerShell Part 2

March 9th, 2009 Niklas Goude 1 comment

This is the fourth Cross Blog post that I’ve made with Mattias and they are getting better and better.

Now, we are heading onto MOSS and the SiteDirectory. Scripting the SiteDirectory is basically the same as scripting a list with items. The fun part is checking the “Approved” value set by an administrator or by someone with the right credentials. The Approved Status can be set to: Approved, Rejected or Pending (default). In PowerShell, the values will be 0, 1, 2 (default). so if we want to check for items that are approved, we check for items that equal 0.

check-sitedirectory01

I’ve included a couple of if else statements that check if the Site is Approved, if the New Site already exists, If the Parent Site Url is valid and so on. An example is if you approve a site that has the following Url:

http://Sharepoint/SiteThatDoesnExist/SiteToCreate

The script won’t create the Site since it’s parent doesn’t exist and will instead prompt you with a recommendation to either create the Parent Site or change the item value.

Script Parameters:

  • -Url Url to SharePoint (Required)
  • -Web Relative Url to SiteDirectory (Required)
  • -List List containing information regarding Sites (Required)
  • -Template Template to use when creating New Sites (Required)
  • -help Prints the HelpFile (Optional)

If you are unsure of whitch Template to use, you can always run the following function to find out which templates are available on your SharePoint Server:


function Get-Templates([string]`$Url) {

	$SPSite = New-Object Microsoft.SharePoint.SPSite($Url)
	$SPSite.GetWebTemplates(1033) | Select Name, Description
	$SPSite.Dispose()
}

PS > Get-Templates http://SharePoint

Now with the basic script procedure in place, we can start Approving sites and scripting them into SharePoint. Start by Approving a Site.

check-sitedirectory03

Now if we check out the Sites list, the Item will be Approved.

check-sitedirectory04

Next, start up PowerShell and trigger the script. Change the Arguments to fit your environment. Run the script.

check-sitedirectory05

And if you check the Url specified in the Item thats Approved, the New Site will have been created.

check-sitedirectory06

Here’s an example on running the script:


PS > .\Check-SiteDirectory.ps1 -Url http://makanigo -Web SiteDirectory -List Sites -Template STS#0

PS >  .\Check-SiteDirectory.ps1 -help

Click here to Download the Script

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Set-Theme.ps1, Set Theme in Sharepoint using PowerShell

March 8th, 2009 Niklas Goude No comments

I wrote a blog post about this a couple of months ago, so here’s an updated script version that let’s you change theme on your SharePoint sites. It’s pretty straight forward and it includes a help function that explains how to use the Script.

Let’s say you have a site http://wss/Teams/TeamWiki. You get a request from your collegues to change the theme to BELLTOWN, since they like it more than the Default SharePoint theme. as an admin, you can either start Internet Explorer, browse to the site in question and Change the Theme through Site Settings or you can fancy off with a PowerShell script that does the work for you.

It might seem a little overkill to start up PowerShell and change the theme on a site when it’s almost as easy as browsing to the site and changing the theme manually.. But, what if you have 10 different TeamWikis on various locations and you have to change all of them?

Here’s an example on running the script on a site. Below is a Screenshot of the site before the script is run.

sharepoint-20

Running the following command:


PS > Set-Theme.ps1 -Url http://wss -Web Teams/TeamWiki -Theme BELLTOWN

Changes the Theme to this:

sharepoint-21

If you want to display the helpfile, simply type:


PS > Set-Theme.ps1 -help

Click here to download the Script.

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Export a list with all the sites in a site collection part 2

February 23rd, 2009 Niklas Goude No comments

This is a follow-up on Part 1 by Mattias Karlssons

As Mattias mentioned, generating a list with Site information is a feature that many people ask for. It’s possible to get the information from the Site Hierarchy or the Site Content and Structure, as Mattias shows in his post

I’m going to show you how to retrieve the information through PowerShell and also provide a script that loops through each site and automates this.

First off, PowerShell can retrieve a great amount of information about Sites. If you run a simple command such as:


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://yoursite"); $SPSite.AllWebs; $SPSite.Dispose()

You will get tons of information from every Site in your collection. The scipt that I’ve made for this post gathers the following information from each site:

  • Name
  • Title
  • Description
  • Theme
  • WebTemplate
  • Author
  • Created
  • Modified
  • Sites
  • Users
  • ParentWeb
  • Url
  • ServerRelativeUrl
  • ID

I’ve also added a switch -ToCsv, that lets you write the information to a Csv file instead of writing it to the PS Host.

Running The Script:


PS > ./Get-SiteInformation.ps1 -Url http://wss

PS > ./Get-SiteInformation.ps1 -Url http://wss -ToCsv

PS > ./Get-SiteInformation.ps1 -help

Download the Script Here

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Remove Sharepoint Users Programmatically Part 2

February 16th, 2009 Niklas Goude No comments

Mattias Described the Scenario in part 1 of this post

Following up on his blog post, I’m going to descrbibe how to script this through SharePoint.

Starting off, we connect to the Site that we believe the User Object is in. Then we create a simple If Else statement that checks if the User Exists, and If so, delete the User.

Here’s the function used in the script.


function RemoveUser([string]$Site, [string]$SiteCollection, [string]$User) {

	# GAC

	[System.Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null
	[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") | Out-Null

	# Connect To Sharepoint

	$SPSite = New-Object Microsoft.SharePoint.SPSite($Site)
	$OpenWeb = $SPSite.OpenWeb($SiteCollection)

	# Check if User Exists in Site

	if ($OpenWeb.SiteUsers | Where {$_.LoginName -eq $User}) {
		$User = $OpenWeb.SiteUsers | Where {$_.LoginName -eq $User}
		$OpenWeb.SiteUsers.Remove($User)

		Write-Host "User: $User Successfully Removed from Site: $Site/$SiteCollection"
	} else {
	Write-Host "User: $User Does not exist on Site: $Site/$SiteCollection"
	}
	$SPSite.Dispose()
	$OpenWeb.Dispose()
}

Here’s a script that automates these steps.

Usage:


PS > Remove-SPUser.ps1 -Site http://wss -SiteCollection Test -User Domain\User

PS > Remove-SPUser.ps1 -help


Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Batch Creation of Sharepoint Sites Part 2

February 9th, 2009 Niklas Goude No comments

This is the second part of a Post started by Mattias Karlsson. Click Here to See Part One

Following on Mattias lead, I’m going to describe how to build a script that automates
the creation of 700+ Sites in sharepoint.

The scenario is well described by Mattias so I’m just going to dig directly into the code.

The first thing we want to consider is the Csv file. Since we work in a Swedish / Finnish Company, there are alot of funny looking characters and non-friendly names that could cause a problem in sharepoint. So step one is getting rid of all funnies. This is a perfect job for the -replace operator.

sharepoint-19

Importing the csv File to PowerShell is done through the Import-Csv CmdLet, as soon as we have imported the Csv file, we can edit each line in it.

There are basically 2 steps that we want to do in Sharepoint, Adding information to a Directory List and creating Sites. The Directory list can be treated in the same way as we altered Custom Lists in this post.

The only “new” item that we want to add now is the URL, which takes 2 arguments, URL and Description.

The Connections to Sharepoint are done in the same way as in previous examples, just make sure to change which list you want to connect to and where your SiteDirectory is.

Creating Sites is described in this post. What’s new in this example is the Template that we want to use. In order to tell SharePoint that we want to build our sites based on a template file, we have to add the template as an argument to the Add() method.

Now that we have gone through all the techniques set and ready, let’s put it all togheter in a ps1 script. The script consists of 3 functions, one Help function that describes how to use the ps1 script, one Csv function that imports the csv file and prepares it and finally a function that adds all data to sharepoint.

Click here to download the Script.

Click here to download a template Csv File

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Hiding a ListField in NewForm/EditForm in Sharepoint

January 13th, 2009 Niklas Goude 2 comments

Hiding a Field can be useful if you don’t want your Users to be able to edit a specific field. Mattias Karlsson, a friend of mine, describes a step-by-step on achieving this on his blog. In this Post, I’m going to describe how to do it through PowerShell. First make a connection to the specific Field, then simply set the ShowInNewForm and ShowInEditForm properties to $false. This will hide the fields from the User when the user is trying to create or edit a List Item.

The image below shows the list that I’m going to edit. I will remove the UserField so that Users editing Items in this List won’t be able to edit the UserField

sharepoint-171

We can hide the fields through a simple function.


function Hide-SPField([string]$url, [string]$List, [string]$Field) {
  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

  $SPSite = New-Object Microsoft.SharePoint.SPSite($url)
  $OpenWeb = $SPSite.OpenWeb()

  $OpenList = $OpenWeb.Lists[$List]

  $OpenField = $OpenList.Fields[$Field]
  $OpenField.ShowInNewForm = $False
  $OpenField.ShowInEditForm = $False
  $OpenField.Update()

  $SPSite.Dispose()
  $OpenWeb.Dispose()
}

Hide-SPField -url http://moss -List "My Custom List" -Field "UserField"

Now, when the user clicks on New Item or Edit Item, the UserField won’t be visible.

sharepoint-18

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Add Site to TopNavigationBar in Sharepoint

January 8th, 2009 Niklas Goude No comments

When Adding a site to the TopNavigationBar, we need to create a New-Object using Navigation.SPNavigationNode. Here’s an example on adding a site to the TopNavigationBar. This is basically the same as when adding the Site to the QuickLaunch.


function Add-SPSiteToTopNav([string]$url,[string]$Site,[string]$SiteURL) {

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

  $SPSite = New-Object Microsoft.SharePoint.SPSite($url)
  $OpenWeb = $SpSite.OpenWeb()

  $TopNavBar = $OpenWeb.Navigation.TopNavigationBar

  $Node = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode $Site, $SiteUrl, 1
  $TopNavBar.AddAsLast($Node)

  $SPSite.Dispose()
  $OpenWeb.Dispose()
}

Add-SPSiteToTopNav -url http://wss -Site TheBlog -SiteURL http://wss/TheBlog

sharepoint-16

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Add Site to QuickLaunch in Sharepoint

January 8th, 2009 Niklas Goude 1 comment

When Adding a site to the QuickLaunch, we need to create a New-Object using Navigation.SPNavigationNode. Here’s an example on adding a site to the QuickLaunch.


function Add-SPSiteToQuickLaunch([string]$url, [string]$Site, [string]$SiteURL) {

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

  $SPSite = New-Object Microsoft.SharePoint.SPSite($url)
  $OpenWeb = $SpSite.OpenWeb()

  $QuickLaunch = $OpenWeb.Navigation.QuickLaunch
  $Node = New-Object Microsoft.SharePoint.Navigation.SPNavigationNode $Site, $SiteURL, 1
  $QuickLaunch.AddAsLast($node)

  $SPSite.Dispose()
  $OpenWeb.Dispose()
}

Add-SPSiteToQuickLaunch -url http://wss -Site TheBlog -SiteURL http://wss/TheBlog

sharepoint-15

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Create a new Site in Sharepoint

January 8th, 2009 Niklas Goude 2 comments

Adding new sites to our Portal is our next step. We do this using the add() method on AllWebs.
Note that there are a couple of values that we have to consider.
First three values are strings, staring with url, title and then description. next, we got the site language.
Then theres site template. Here you can use a few different templates depending on what kind of site you want.
In WSS 3.0 you can choose from the following Site Templates:


PS > [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $SPSite.GetWebTemplates(1033) | Select Name, Description; $SPSite.Dispose()

Name                   Description
----                   -----------
GLOBAL#0               This template is used for initializing a new...
STS#0                  A site for teams to quickly organize, author...
STS#1                  A blank site for you to customize based on y...
STS#2                  A site for colleagues to work together on a ...
MPS#0                  A site to plan, organize, and capture the re...
MPS#1                  A blank meeting site for you to customize ba...
MPS#2                  A site for meetings that track status or mak...
MPS#3                  A site to plan social occasions. It provides...
MPS#4                  A site to plan, organize, and capture the re...
CENTRALADMIN#0         A site for central administration. It provid...
WIKI#0                 A site for a community to brainstorm and sha...
BLOG#0                 A site for a person or team to post ideas, o...

Lets Create a Blog Site. The WebTemplate that we want to use to create a Blog site is BLOG#0. Here's a function that simplifies the creation.


function Create-SPSite([string]$url, [string]$SiteUrl,[string]$Name, [string]$Description, [string]$Template) {
  [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

  $SPSite = New-Object Microsoft.SharePoint.SPSite($url)

  $SPSite.AllWebs.Add($SiteUrl, $Name, $Description, [int]1033, $Template, $FALSE, $FALSE)

  $SPSite.Dispose()
}

Create-SPSite -url http://wss -SiteUrl TheBlog -Description "Blogging is Fun" -Template "BLOG#0"

Now, the Blog site is added to our Sharepoint Portal.

sharepoint-14

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Add Items to a List in Sharepoint

January 8th, 2009 Niklas Goude No comments

Our List contains a couple of different Fields: User,Text,Choice,Lookup and the default Title Field. Let’s start preparing the information that we want to add into our item.

sharepoint-11

The Title Field requires a Text String, so I’m going to set up a variable containing a TextString.

PS > $Title = "Item Title"

When preparing the UserField, we need to tell Sharepoint which user we want in our field,
so we need to create an Object containing the information about the User. In this example, we will add User1.


PS > [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb("/"); $User1 = $OpenWeb.SiteUsers["BPA\User1"]; $OpenWeb.Dispose(); $SPSite.Dispose()
PS > $User1

Name             : User1
Email            : mail@apa.corp
Notes            :
LoginName        : BPA\user1
Groups           : {The New Group}
OwnedGroups      : {}
ID               : 10
Xml              : <User ID="10" Sid="S-1-5-21-2828386465-1027348
                   " Email="mail@apa.corp" Notes="" IsSiteAdmin="
RawSid           : {1, 5, 0, 0...}
Sid              : S-1-5-21-2828386465-1027348953-3114450994-1349
IsSiteAdmin      : False
IsSiteAuditor    : False
IsDomainGroup    : False
Alerts           : {}
UserToken        : Microsoft.SharePoint.SPUserToken
RegionalSettings :
ParentWeb        : Team Site
Roles            : {Contribute, Read}

The Text Field is basically the same as the Title Field.


PS > $Text = "Some Text"

The Choice Field however requires that we enter one of the choices that we created in an earlier blog post.


PS > $Choice = "Second Choice"

The last variable that we want to prepare is the LookupField Value. The List that we are currently working with has a Lookup field that retrieves
information from the "LookupList" List. We need to tell Sharepoint Which item in the "LookupList" that we want to add to our new Item.to
First Let's create a variable holding the information about the "LookupList".


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb("/"); $LookupList = $OpenWeb.Lists["LookupList"]; $OpenWeb.Dispose(); $SPSite.Dispose()

Next, we need to get the specific Item in the list that we want to Lookup. In this example I'll use the Where-Object to retrieve the Item that
I want. It's important to match on a unique value. If you have 2 values with the same name you could use the -and operator to get a more exact matching.


PS > $LookupItem = $LookupList.Items | Where-Object { $_.Name -match 1 }

The LookupField requires that the Item that we want to Lookup is presented in a specific way: ID;#Name
So lets prepare a variable that's presented correctly.


PS > $Lookup = ($LookupItem.ID).ToString() + ";#" + ($LookupItem.Name).ToString()

Now we can create a new item.


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb("/"); $List = $OpenWeb.Lists["My Custom List"]; $OpenWeb.Dispose(); $SPSite.Dispose()

PS > $Item = $List.Items.Add()
PS > $Item["Title"] = "Title"
PS > $Item["UserField"] = $User1
PS > $Item["TextField"] = $Text
PS > $Item["ChoiceField"] = $Choice
PS > $Item["LookupField"] = $Lookup
PS > $Item.Update()

sharepoint-13

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Adding Fields to a List in Sharepoint

January 6th, 2009 Niklas Goude No comments

There are a couple of types that you can add to a list, Single Line of Text, Multiple Lines o Text, Users etc. Here’s how to get a complete list of all available list types:


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $OpenWeb.FieldTypeDefinitionCollection | Select TypeName; $OpenWeb.Dispose(); $SPSite.Dispose()

TypeName
--------
Counter
Text
Note
Choice
MultiChoice
GridChoice
Integer
Number
ModStat
Currency
DateTime
Lookup
Boolean
Threading
ThreadIndex
Guid
Computed
File
Attachments
User
URL
Calculated
Recurrence
CrossProjectLink
ContentTypeId
MultiColumn
LookupMulti
UserMulti
WorkflowStatus
AllDayEvent
WorkflowEventType
PageSeparator

Let’s Add a couple of Fileds to our Custom List. First we have to create a couple of objects that hold the information about the Fields that we want to add


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $User = $OpenWeb.FieldTypeDefinitionCollection["User"]; $OpenWeb.Dispose(); $SPSite.Dispose()

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $Text = $OpenWeb.FieldTypeDefinitionCollection["Text"]; $OpenWeb.Dispose(); $SPSite.Dispose()

Next step is adding the Fields to our List. This is done through the Add() method:


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $List = $OpenWeb.Lists["My Custom List"]; $OpenWeb.Dispose(); $SPSite.Dispose()

PS > $List.Fields.Add("UserField", "User", $User)
PS > $List.Fields.Add("TextField", "Text", $Text)

This Adds the Fields to our Custom list but they don’t show up in Sharepoint. To solve this we have to add them to the Lists View:


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb();$Views = $list.Views["All Items"]; $OpenWeb.Dispose(); $SPSite.Dispose()

PS > $Views.ViewFields.Add("UserField")
PS > $Views.ViewFields.Add("TextField")
PS > $Views.Update()

Adding Text Fields and User fields is rather simple, but say we want to add a Choice field and a LookUp field. This is a little bit tricky. Let’s start with the Choice Field. First, we’ll create the different choices. this is don through the System.Collections.Specialized.StringCollection.


$Choices = New-Object System.Collections.Specialized.StringCollection
$Choices.Add("First Choice")
$Choices.Add("Second Choice")
$Choices.Add("Third Choice")

Now that we have created our Choices, we can go aheead and add them to the Sharepoint list. It’s done a little different than before.


$List.Fields.Add(
	"ChoiceField",
	[Microsoft.SharePoint.SPFieldType]::Choice,
	$FALSE,
	$FALSE,
	$Choices
)

And then update the Views.


$Views = $List.Views["All Items"]
$Views.ViewFields.Add("ChoiceField")
$Views.Update()

Now, lets add a Lookup Field. To do this, we need a List to Lookup the information from. In this example I’ve created a simple List with 3 items in as shown below.

sharepoint-10

First we have to tell Sharepoint which list we want to Lookup the information in.


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb();$LookupList = $OpenWeb.Lists["LookupList"]
PS > $LookupListID = $LookupList.ID

The Method that we are going to use AddLookup(), takes the Lists ID as an argument, so thats why I made a $LookupListID variable to hold this information. Next, we run the method.


PS > $List.Fields.AddLookup("LookupField",$ID,$FALSE)

PS > $Views = $list.Views["All Items"]
PS > $Views.ViewFields.Add(“LookupField”)
PS > $Views.Update()

The List should look something like this now.

sharepoint-11

sharepoint-12

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Adding Lists to the QuickLaunch in Sharepoint

January 6th, 2009 Niklas Goude 1 comment

By default, the lists that we create through PowerShell are not in the quicklaunch, so we have to tell SharePoint that we want it there. The OnQuickLaunch value is set to $false so changing this to $true will add our Custom List to the Quicklaunch. We also need to allow ContentTypes in order to add our fields. Don’t forget to use the update() method to set the value.


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb("/"); $List = $OpenWeb.Lists["My Custom List"]; $OpenWeb.Dispose(); $SPSite.Dispose()

PS > $List.OnQuickLaunch = $true
PS > $List.ContentTypesEnabled = $true
PS > $List.Update()

Now our list is added to the QuickLaunchBar

sharepoint-08

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Creating A Custom List in Sharepoint

January 6th, 2009 Niklas Goude No comments

Okay, so now we’ve got our users and groups in place. Let’s start extending the Site a little. Starting off, let’s look at Custom Lists. Custom Lists are like excel sheets where we can store information in columns. There are lots of different types of data that we can store, such as: Single line of text, Choice, Numers, Date and Time, Lookup (Information already on the site) and so on.. So let’s start by creating a custom list.

When we create a new lisy of any kind, SharePoint needs to know what kind of list we want. If you check out the ListTemplates property you can see that there are many different types of lists that we can choose from.


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $OpenWeb.ListTemplates | Select Name, Description; $OpenWeb.Dispose(); $SPSite.Dispose()


Name                             Description
----                             -----------
Document Library                 Create a document library when you ha...
Form Library                     Create a form library when you have X...
Wiki Page Library                Create a Wiki page library when you w...
Picture Library                  Create a picture library when you hav...
Links                            Create a links list when you have lin...
Announcements                    Create an announcements list when you...
Contacts                         Create a contacts list when you want ...
Calendar                         Create a calendar list when you want ...
Discussion Board                 Create a discussion board when you wa...
Tasks                            Create a tasks list when you want to ...
Project Tasks                    Create a project tasks list when you ...
Issue Tracking                   Create an issue tracking list when yo...
Custom List                      Create a custom list when you want to...
Custom List in Datasheet View    Create a custom list when you want to...
Survey                           Create a survey when you want to poll...
Workflow History                 This list is used by SharePoint to st...
Custom Workflow Process          Custom Workflow Process tracking list...
No Code Workflows                Gallery for storing No Code Workflows...
DataSources                      Gallery for storing data source defin...

In our case, we’ll use the Custom List. The Strings that are defined are: Title and Description. TemplateType is an object that we have to create around the specific template that we want to use.


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $TemplateType = $OpenWeb.ListTemplates["Custom List"]; $OpenWeb.Dispose(); $SPSite.Dispose()

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $OpenWeb.Lists.Add("My Custom List","Description Of My Custom List",$TemplateType); $OpenWeb.Dispose(); $SPSite.Dispose()

If we Check out our Site now, we will have a new “Custom” list added.

sharepoint-07

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Adding User to Group in Sharepoint

January 6th, 2009 Niklas Goude No comments

Adding Users to a specified group in Sharepoint can be done through the AddUser method on a specific group.

First we have to create a variable around the group that we want to work with, in this example we will use the group that was created in the Adding a Custom Group to Sharepoint post.


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $TheNewGroup = $OpenWeb.SiteGroups | Where-Object {$_.Name -match "The New Group"}; $OpenWeb.Dispose(); $SPSite.Dispose()

Now that we have an object containing our group we need all the users that we want to add to the group. You can filter out specific users with the Where-Object CmdLet, but in this example im just going for all users. I only need the LoginName, Email and Name of the User so I only select those properties with the Select-Object CmdLet


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $User = $OpenWeb.Users | Select Name, Email, LoginName; $OpenWeb.Dispose(); $SPSite.Dispose()

Last step is to add the Users in my object to The New Group.


PS > $User | ForEach-Object {
	$TheNewGroup.AddUser(
		$_.LoginName,
		$_.Email,
		$_.Name,
		""
	)
}

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Adding Users to Sharepoint

January 6th, 2009 Niklas Goude 1 comment

Adding Users from Active-Directory into Sharepoint is done in 2 steps. First we will need to Get the information required from Active-Directory and then we need to Add the informtaion into Sharepoint.

Lets start with Active-Directory. Below is an image of the Active-Directory Design in this example:

active-directory-01

Since we want to Get the User information we need to connect to the correct OU through ADSI. The Connection string to the User OU that we want to access would look like this

LDAP://OU=Site1 Users,OU=Site1,OU=Sites,DC=BPA,DC=CORP

Here’s how to connect to the OU through PowerShell:

PS > $ConnectionString = "LDAP://OU=Site1 Users,OU=Site1,OU=Sites,DC=BPA,DC=CORP"
PS > $AD = [adsi]$ConnectionString
PS > $AD
distinguishedName
-----------------
{OU=Site1 Users,OU=Site1,OU=Sites,DC=bpa,DC=corp}

This shows that we have connected to the correct OU. To retrieve information about the Users in the OU we have to access the children within the object.

PS > $AD.PsBase.Children
distinguishedName
-----------------
{CN=user1,OU=Site1 Users,OU=Site1,OU=Sites,DC=bpa,DC=corp}
{CN=user2,OU=Site1 Users,OU=Site1,OU=Sites,DC=bpa,DC=corp}
{CN=user3,OU=Site1 Users,OU=Site1,OU=Sites,DC=bpa,DC=corp}
{CN=User4,OU=Site1 Users,OU=Site1,OU=Sites,DC=bpa,DC=corp}

Now that we have all the Users in the OU we can start collecting the information. But first let’s check what we need. The User items in WSS 3.0 have a couple of settable values and not all values are available Properties in Active-Directory.

sharepoint-05

Sharepoint actually looks up Department and Job Title if they exist in Active-Directory so we dont have to bother about that. What we do need is the Users loginname, mail and name.
To retrieve the information, we will create a filter that takes the information from Active-Directory.

PS > filter UserProperties {
     $_ | select @{ name='sAMAccountName'; Expression={$_.sAMAccountName} },
     @{ name='mail'; Expression={$_.mail} },
     @{ name='displayName'; Expression={$_.displayName} }
 }

Next we will run through all Child objects in the OU and filter them into a new Custom Object.

PS > $User = $AD.PsBase.Children | UserProperties
PS > $User
sAMAccountName                          mail                                    displayName
--------------                          ----                                    -----------
user1                                   user1@mail.com                          user1
user2                                   user2@mail.com                          user2
user3                                   user3@mail.com                          user3
user4                                   user4@mail.com                          User4

Now that we have the User information stored in a PowerShell object, we can use it to create the users in Sharepoint. When adding users to Sharepoint, we have to consider which Role ther Users should have. there are a few available roles to choose from. We can get a list of all roles through the Roles Property.


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $OpenWeb.Roles | Select Name, Description; $OpenWeb.Dispose(); $SPSite.Dispose()


Name                                                        Description
----                                                        -----------
Full Control                                                Has full control.
Design                                                      Can view, add, update, delete, approve...
Contribute                                                  Can view, add, update, and delete.
Read                                                        Can view only.
Limited Access                                              Can view specific lists, document libraries...

In this example, we will use the Read Role. To add the users to Sharepoint we use a function.


function Add-SPUser([string]$url, [string]$Role, [string]$Domain, [string]$sAMAccountName, [string]$Mail, [string]$DisplayName) {

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

  $SPSite = New-Object Microsoft.SharePoint.SPSite($url);
  $OpenWeb = $SpSite.OpenWeb(); $OpenWeb.Roles | Select Name, Description; $OpenWeb.Dispose(); $SPSite.Dispose()

  $OpenWeb.Roles[$Role].AddUser(
    $Domain + $sAMAccountName,
    $Mail,
    $DisplayName,
    ""
  )
  $OpenWeb.Dispose()
  $SPSite.Dispose()
}

PS > $User | foreach-object {
  Add-SPUser -url http://wss -Role Read -Domain bpa -sAMAccountName $_.sAMAccountName -Mail $_.Mail -DisplayName $_.DisplayName
}

Now the users are added to Sharepoint. Note that Job Title and Department are added automatically, if the values exist in Active-Directory.

sharepoint-06

Rating 3.00 out of 5
[?]

Adding A Custom Group to Sharepoint

January 6th, 2009 Niklas Goude 1 comment

SharePoint has a couple of default groups but say we want to create our own group. The values that we need to assign are:

String name
SPMember owner
SPUser defaultUser
String description

Name and description are strings. SPMemeber Owner and SPMember defaultUser are a little tricky.. You have to retrieve these from existing Users in SharePoint. In this example we will add the Admin account to the group.


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite(http://wss); $OpenWeb = $SPSite.OpenWeb(); $OpenWeb.SiteGroups.Add("The New Group", $OpenWeb.SiteUsers["BPA\sharepoint"], $OpenWeb.SiteUsers["BPA\sharepoint"],"Description of The New Group"); $OpenWeb.Update(); $OpenWeb.Dispose(); $SPSite.Dispose()

If you look in Sharepoint through Internet Explorer, the group will only be visible if you navigate to People and Groups: All Groups as shown in the screenshot below.

sharepoint-03

 

To add the group to the QuickLaunch bar, we have to add our New Group to the Associated Groups.

 


PS > $SPSite = New-Object Microsoft.SharePoint.SPSite(http://wss); $OpenWeb = $SPSite.OpenWeb(); $OpenWeb.AssociatedGroups.Add($OpenWeb.SiteGroups["The New Group"]); $OpenWeb.Update(); $OpenWeb.Dispose(); $SPSite.Dispose()

Now the group will be visible in the QuickLaunch Bar.

sharepoint-04

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags:

Changing Theme in Sharepoint

January 6th, 2009 Niklas Goude No comments

Changing the theme of a Sharepoint site is an easy task through PowerShell. there are a couple of available themes that you can choose from.

You can use the following themes in WSS 3.0

Beltown
Breeze
Cardinal
Citrus
Claasic
Default Theme
Granite
Jet
Lacquer
Lichen
Obsidian
Petal
Plastic
Reflector
Simple
Verdant
Vintage
Weat

To change Theme, we can use the ApplyTheme() method. Before we use the method we define which site we want to change theme on, In my case, I’ll change it on the TopSite.


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

PS > $SPSite = New-Object Microsoft.SharePoint.SPSite("http://wss"); $OpenWeb = $SpSite.OpenWeb(); $OpenWeb.ApplyTheme("Obsidian"); $OpenWeb.Dispose(); $SPSite.Dispose()


If we look at our site through Internet Explorer, we can see the change:

sharepoint-02

Rating 3.00 out of 5
[?]
Categories: Sharepoint Tags: