Posts Tagged ‘PowerShell’
PowerShell Foreach vs ForEach-Object
There are two variants of ‘for each’ in PowerShell:
Foreach statement: iterates over a collection of objects
ForEach-Object: obtains its entries from the pipeline
At first they both seemed to do the job, but there are some differences.
Let’s do a test with a simple array of items and loop through it using both foreach methods. To measure the time elapsed to loop the array the Measure-Command is used.
$items = 1,2,3,4,5,6,7,8,9,0,10,12,13,14,15,52,58,41,59,841,5,4,1
Write-Host "ForEach-Object: "
(Measure-Command { `
$items | ForEach-Object { `
"Item: $_" `
}}).totalmilliseconds
Write-Host "Foreach: "
(Measure-Command { `
Foreach ($item in $items) { `
"Item: $element" `
}}).totalmilliseconds
The results differ a lot!
When to use which method?
When the items of the array are known at forehand, like in the test, foreach is the better approach because of the speed. This kind of speed can only be reached when all the objects are already known and stored in a variable.
ForEach-Object is a different story. When the items have to be collected before the loop starts and this can take a while: use ForEach-Object.
This method processes the objects collected in the array directly when available and doesn’t wait until all objects are collected.
How to retrieve document set version history
Document set versions are slightly different than item versions. Document sets can be managed by a separate ribbon tab called Document Set and group called Manage.

To create a version of a document set the action Capture Version in this part of the ribbon has to be selected. When selecting the following screen will be shown:

To use versioning of a document set (and items) versioning has to be enabled on the library.
After selecting a version option (when major/minor enabled), adding some comment and selecting the Ok button a document set version is created. To view the versions of the document set the action Version History can be selected in the ribbon.

In this screen the first column displayed is No. This is not the regular version column of the library, but a totally different one. When creating a document set version the version column of the library doesn’t change, only the No value.
That’s nice, but where is the version of the document set actually stored?
The version(s) of a document set are stored in the propertybag of the item itself.
To analyze settings I always start up PowerShell first to check on things. Just because it’s quick and easy. When I get what I want from PowerShell it’s easily turned into C# code. I followed the same procedure to get to the storage of document set versions. Since I couldn’t find the version anywhere in the UI, my first guess was checking the propertybag keys.
$site=Get-SPSite "http://sp2010dev"
$docList = $site.RootWeb.Lists.TryGetList("Documents");
$item = $docList.Items.GetItemById(2)
$prop = $item.Properties
Often I use PowerGui Script Editor which gives an excellent overview of variables:
While scrolling through the property keys I noticed a key named snapshots. By checking out the value of that key I knew I found it!
The following PowerShell command can be used to get the value of the snapshot key:
$item.Properties.get_Item("snapshots")
The version history is stored in xml:
<SnapshotCollection NextSnapshotNumber="3" NextInternalId="1">
<Items />
<Snapshots>
<Snapshot Label="2" Major="True" Created="08/21/2011 07:50:56" By="username">
<Comments>Another version of the document set.</Comments>
<Fields>
<Field Id="8553196d-ec8d-4564-9861-3dbe931050c8">Document set name</Field>
<Field Id="fa564e0f-0c70-4ab9-b863-0177e6ddd247">Document set name</Field>
<Field Id="cbb92da4-fd46-4c7d-af6c-3128c2a5576e">Add a description here.</Field>
</Fields>
<SnapshotItems />
</Snapshot>
<Snapshot Label="1" Major="True" Created="08/21/2011 07:50:20" By="username">
<Comments>This is the first version of this document set.</Comments>
<Fields>
<Field Id="8553196d-ec8d-4564-9861-3dbe931050c8">Document set name</Field>
<Field Id="fa564e0f-0c70-4ab9-b863-0177e6ddd247">Document set name</Field>
<Field Id="cbb92da4-fd46-4c7d-af6c-3128c2a5576e" />
</Fields>
<SnapshotItems />
</Snapshot>
</Snapshots>
</SnapshotCollection>
The Snapshot element with Label attribute 1 is the first version. The comment is displayed and the fields and values of the document set.
The Snapshot element with Label attribute 2 is the second version. The same items are displayed with the addition of the value of the description ‘Add a description here’. That’s what I changed before creating the second version.
The attribute NextSnapshotNumber holds the value of the version number that will be created when creating another version, 3 in this case.
Summary
Document set versions are different than regular item versions. The version history of a document set is stored in the propertybag of the document set itself as xml.
PowerShell – Choose between colored host text or write to an output file? Not anymore!
In PowerShell multiple Write statements are available. The two statements I want to address are Write-Host and Write-Output.
What do these two do?
Write-Host: Writes customized output to a host
Write-Output: Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console
An example of Write-Host
Write-Host "Write-Host statement..."
The result displayed in the host
An example of Write-Output
Write-Output "Write-Output statement..."
The result displayed in the host
At this point there is no difference in the result of these two statements.
Write-Host with ForegroundColor
A nice parameter of Write-Host is -ForegroundColor. Using this parameter with a color, the text displayed in the host has the color specified. I find this very useful to quickly see if a script has succeeded or failed. I always display the success message in green, the failed message in red.
To show this the existence of a SPList will be checked. If it doesn´t exist, it will be created using the following statement:
$sampleListName = "PS List"
$siteUrl=http://sp2010dev
$site = Get-SPSite $siteUrl
$web = $site.RootWeb</pre>
function CreateList($listName){
$web.Lists.Add($listName, "Description for list", [Microsoft.SharePoint.SPListTemplateType]::GenericList)
}
function CheckIfListExists(){
$currentList = $web.Lists.TryGetList($sampleListName)
if($currentList -ne $null){
Write-Host "List exists" -ForegroundColor Green
}
else{
Write-Host "List doesn't exist, creating now..." -ForegroundColor Red
CreateList $sampleListName
Write-Host "Check if list exist..."
CheckIfListExists
}
}
Write-Host "Calling CheckIfListExists ..."
CheckIfListExists
If the list exists a message with green colored text will appear: ‘List exists’, else a message with red colored text will appear: ‘List doesn’t exist, creating now…’, followed by the actual creation of the list. After this the existence of the list is check again. As you can see if the list creation fails the code will be stuck in an infinite loop, so don´t use this as production code…
Outcome when the list doesn´t exist and is created:
Outcome when the list already exists:<picture PSWrite02>
Write-Output with output to file
A nice option of Write-Output is the possibility to write the output to a file on the filesystem.
$file = "C:\_Tools\OutputFile.txt" Write-Output "Write-Output statement..." Write-Output "Write-Output statement..." | Out-File $file
The first Write-Output statement writes the output to the host, the second to the file (but not to the host).
Best of both worlds?
Ofcourse Write-Host as well as Write-Output has a lot more options to use, but I want to point out something here.
Write-Host can write colored messages to the host, but it can’t write output to a file.
Write-Output can’t write colored messages to the host, but it can write output to a file.
What if I want to:
write colored messages to the host if I decide to output to the host AND
write messages to a file just by using ‘| Out-File $file’
With the current possibilities of both operations I have to choose between:
1. colored messages (and nothing written to the output file) or put the output to a file and host, but no colored messages displayed in the host
2. write double statements; Write-Host with -ForeGroundColor to write the colored output to the host and Write-Output to write the output to a file when using ‘| Out-File $file’.
Let me clarify the second option with an example.
Write-Output "Write-Output statement..." | Out-File $file Write-Host "Write-Host statement..." -ForegroundColor Blue
Write-Output writes the message to the file specified in $file and is not written to the host.
Write-Host writes the message to the host in the color blue.
Just as expected and just want I wanted. But I have to write the messages twice.
Another option:
Write-Output "Write-Output statement..." Write-Host "Write-Host statement..." -ForegroundColor Blue
The code above is saved in a file and called by:
PS C:\_Tools> .\PSScriptFile.ps1
Result: messages appear twice in the host.
Output it to a file:
PS C:\_Tools> .\PSScriptFile.ps1 | Out-File $file
Result: No message in the host, but a message in the file!
Still, the messages have to be written twice in the file: Write-Host and Write-Output…
Do I really have to write all the messages twice to show them colored in the host and write them to an output file?
Actually, there is no possibility to make Write-Host write to an output file.
But the host itself can be accessed to change its text color (and more) and use Write-Output to write to the host (in color!) and to an output file.
The host itself can be accessed by $Host.
$Host.Name
When using PowerGUI Script Editor the results of the above statement is: PowerGUIScriptEditorHost
Executing the same statement in the console the result is: ConsoleHost
That’s awesome, $Host knows who he is!
Let’s try to get the text color of the host:
$currentColor = $Host.UI.RawUI.ForegroundColor
PowerGUI Script Editor:
Console:
So what about changing the text color of the host?
function WriteCustomOutput($message, [System.ConsoleColor]$foregroundcolor)
{
currentColor = $Host.UI.RawUI.ForegroundColor
$Host.UI.RawUI.ForegroundColor = $foregroundcolor
if ($message)
{
Write-Output $message
}
$Host.UI.RawUI.ForegroundColor = $currentColor
}
WriteCustomOutput -message "WriteColoredOutput statement..." -foregroundcolor Green
And the result in the host:
Let’s save the code to a file and call the file from the console:
And will the output be written to an output file when using the statement:
.\PSWriteCustomOutput.ps1 | Out-File OutputFile.txt
Yes it is written to the file:
Summary
Write-Host and Write-Output are very simple and useful statements. Sometimes the best of both is wished for.
With some creativity you can have both. Use WriteCustomOutput!
Imtech
Branche: ICT & Internet dienstverlening
Februari 2011 – mei 2011
Lead developer SharePoint
Oasen maakt drinkwater voor 750.000 mensen en 7.200 bedrijven in het oosten van Zuid-Holland. Het voorzieningsgebied bestaat uit 32 gemeenten.
Op dit moment is de publieke website van Oasen gebaseerd op MOSS2007. Door een nieuwe visie op de vindbaarheid van content, indeling, interactie met de klant en dynamiek is er een nieuwe website ontwikkeld op basis van SharePoint 2010. Een derde partij heeft de ontwikkeling van het design op zich genomen. Het team van Imtech aangevuld met Anita mag de website ontwikkelen op basis van het User Experience document wat het design laat zien.
Basis voor de technische oplossing voor de nieuwe website zijn het User Experience document en de website van Oasen. De technische oplossing en implementatie van de nieuwe website zijn bepaald door het projectteam. Anita is verantwoordelijk voor deze technische keuzes en oplossingen.
Het projectteam bestaat uit een projectleider, consultant, lead engineer, twee engineers en drie designers. Anita vervult de rol van lead engineer. Scrum wordt toegepast met sprints van 2 a 3 weken. De totale doorlooptijd van het project is 9 weken.
Er wordt waar mogelijk gebruik gemaakt van standaard SharePoint componenten, welke aangepast en uitgebreid worden om de exact gewenste functionaliteit te verkrijgen.
De nieuwe website van Oasen maakt zeer intensief gebruik van de SharePoint Search functionaliteit. Dit is de technische basis en komt in vele onderdelen van de website terug. Content in de website wordt voorzien van metadata (onder andere tags) om de vindbaarheid te verbeteren en om de content te kunnen verfijnen op basis van deze tags. De content is onderverdeeld in verschillende types als nieuws, artikelen, applicaties, veelgestelde vragen, foto’s, video’s en storingen.
De traditionele navigatie binnen een website door middel van een menustructuur is grotendeels vervangen: er wordt gebruik gemaakt van de mogelijkheid om content te verfijnen op basis van tags. Om dit te realiseren wordt er gebruik gemaakt van het standaard RefinementPanel met een aangepaste filterdefinitie (inclusief bijbehorende managed/crawled properties) en xslt. Buiten het standaard RefinementPanel is er een custom refiner ontwikkeld welke content binnen een bepaalde tijdsperiode filtert.
Om de content te tonen is het Core Results webpart diverse keren geimplementeerd in een zeer aangepaste vorm. Content wordt dynamisch toegevoegd aan de zoekresultaten op de verschillende pagina’s middels intensief gebruik van http handlers, jQuery en JSON. Vanuit de zoekresultaten kan er genavigeerd worden naar het weergegeven type content. Foto’s en video’s worden getoond in een lightbox met extra informatie over het getoonde item.
Op de website wordt intensief gebruik gemaakt van het Content Query webpart. De nieuwe ‘slots’ functionaliteit wordt toegepast en er zijn nieuwe xslt item styles ontwikkeld.
Uiteraard is er een masterpage ontwikkeld en diverse page layouts om de website structuur te geven en van een consistente look & feel te voorzien in de stijl welke bij Oasen past. Het design van de website is zeer vernieuwend en dynamisch en brengt de nodige uitdagingen met zich mee in combinatie met SharePoint. Er is geen onderdeel in de website wat overeenkomt met standaard SharePoint design.
Buiten nieuw ontwikkelde functionaliteit zijn er diverse bestaande modules gemigreerd naar de nieuwe site. Als klant van Oasen kan er gebruik worden gemaakt van modules als het doorgeven van meterstanden of een verhuizing, het rekeningnummer wijzigen en het voorschot aanpassen.
Verder worden er grafieken over het waterverbruik getoond. Hier kan bijvoorbeeld mee worden bepaald wanneer de rust in een belangrijke voetbalwedstrijd is.
Diverse watermeters worden getoond om de hoeveelheid water aan te geven welke Oasen levert in diverse regio’s. Deze meters worden grafisch weergegeven door middel van flash technologie. Diverse modules hebben een BizTalk koppeling met achterliggende systemen.
Naast de beschreven (basis) functionaliteit zijn er vele onderdelen ontwikkeld, welke binnenkort op de website van Oasen zullen worden gepubliceerd op http://www.oasen.nl
Diverse onderdelen van SharePoint zijn gebruikt om de functionaliteit te kunnen realiseren, zoals sitecolumns, contenttypes, listinstances, jQuery, HTTP Handlers, application pages, css, xslt, page layouts, masterpage, custom actions, eventreceivers, workflows, user controls, webcontrols, webparts, delegates, timerjobs, Excel services.
De website van Oasen is een publieke website, waarbij performance en optimalisatie uitermate belangrijk zijn.
Voor de registratie van de te realiseren onderdelen is Team Foundation Server 2010 gebruikt. Anita is verantwoordelijk voor het bepalen van te realiseren onderdelen in elke sprint en het creeren van taken gerelateerd aan deze sprint backlog items. Daar Anita verantwoordelijk is voor de technische keuzes in het project is het van belang dat zij ook de inhoud van de sprints bepaalt, zodat er snel een basis voor de website staat. Mede omdat de doorlooptijd van het project maar 9 weken is. Voordat een sprint start wordt in een sessie met de engineers en designer de sprint backlog items verdeeld met in achtneming van de beschikbare uren van de projectleden en de te verdelen items. Tijdens het project is Anita verantwoordelijk voor de planning, voortgang en kwaliteit van het opgeleverde. Anita straalt rust uit over het team en staat ten alle tijde open voor vragen van elk lid van het projectteam.
SharePoint Server 2010, Visual Studio 2010, jQuery, JSON, xslt, Excel services, Team Foundation Server 2010, TFS Sidekicks, Imtech OCD, Scrum.
Developer Dashboard
The Developer Dashboard is great to see what’s going on when loading a page in SharePoint 2010.
Windows PowerShell is THE application to enable/disable the Developer Dashboard in SharePoint 2010. Here are the commands:
$service=[Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashBoardSettings;
$service.DisplayLevel = “On”;
$service.Update();
The displaylevel can be On, Off or OnDemand. When set to OnDemand an icon is added to the top right corner to toggle the On/Off state of the Developer Dashboard (enlarged):

The DisplayLevel is an enumerator used to specify behavior aspects of the Developer Dashboard, check also MSDN:
| Member | Description |
| Off | Enumeration value = 0: Dashboard feature is disabled |
| OnDemand | Enumeration value = 1: Dashboard feature is available on request |
| On | Enumeration value = 2: Dashboard feature is enabled |
When you receive the following error:
Unable to find type [Microsoft.SharePoint.Administration.SPWebService]: make sure that the assembly containing this type is loaded.
Two solutions:
- You are running Windows PowerShell in stead of SharePoint 2010 Management Shell:
use SharePoint 2010 Management Shell. - You are running Windows PowerShell in stead of SharePoint 2010 Management Shell:
make Windows PowerShell behave like the SharePoint 2010 Management Shell by running ‘add-pssnapin microsoft.sharepoint.powershell’ in Windows PowerShell.
Want to include some of your own code in the monitoring of the dashboard?
Just wrap it up in a new SPMonitoredScope:
using (SPMonitoredScope scope = new SPMonitoredScope(“MyMonitoring”))
{
//your code to monitor here
}






