About Us

Add a User Profile Property Mapping for SharePoint 2010 Using PowerShell

by Jess Collicott 1. October 2012 18:19

If you have a need to add User Profile property mappings for import / export with Active Directory, or some other Synchronization Connection, you can use the PowerShell script made available from Tehnoon Raza on his MSDN blog:

Mapping User Profile Properties in SharePoint 2010 to LDAP Attributes

This can sometimes be quicker than going through the Central Administration UI.

Find all Alerts in a Site Collection in SharePoint 2010

by Jess Collicott 26. May 2012 00:33

If you have a need to search through a SharePoint 2010 site collection and provide a report on all existing e-mail or SMS Alerts, you can use the following PowerShell script (watch for word wrapping on lines 9, 10, 11, and 12):

   1:  Add-PSSnapin microsoft.sharepoint.powershell
   2:   
   3:  $site = Get-SPSite "http://dlvrn2010/sites/spalerts/"
   4:  $alertResultsCollection = @()
   5:  foreach ($web in $site.AllWebs) {  
   6:      foreach ($alert in $web.Alerts){
   7:          $alertURL = $web.URL + "/" + $alert.ListUrl
   8:          $alertResult = New-Object PSObject

9: $alertResult | Add-Member -type NoteProperty -name "List URL"

-value $alertURL

  10:          $alertResult | Add-Member -type NoteProperty -name "Alert Title" 
       -value $alert.Title

11: $alertResult | Add-Member -type NoteProperty -name "Alert Type"

-value $alert.AlertType

  12:          $alertResult | Add-Member -type NoteProperty -name "Subscribed User"
       -value $alert.User
  13:          $alertResultsCollection += $alertResult
  14:      }
  15:  }
  16:  $site.Dispose()
  17:  $alertResultsCollection
  18:   
  19:  ## Export to CSV
  20:  #$alertResultsCollection | Export-CSV "Alerts.csv"

 

Using the defaults, it will output a table representation of the Alerts it found:

Host-Output

If you uncomment line 20, it will create a CSV file of the same data:

CSV-Output

You can quickly format it to a prettier, sortable report in Excel 2010 by formatting it as a table:

XSLX-Output

Update Active Directory Accounts from a CSV File using PowerShell

by Jess Collicott 6. March 2012 00:27

For instances where there is need to update a specific list of user accounts in Active Directory, it may be ideal to use PowerShell to loop through the list and make the changes for each of the users using the Active Directory Administration Module for PowerShell. For the sake of this example, assume there is a CSV file with a column titled sAMAccountName:

2012-03-05_1713

If we wanted to update the Company attribute in AD for each of these users, we could use the following PowerShell script to read in the list of users, and use Get-ADUser to get the specific AD account object, and then pass to Set-ADUser to make the actual change:

1 Import-module ActiveDirectory 2 3 $userList = Import-Csv '.\List of Users.csv' 4 5 foreach ($user in $userList){ 6 Get-ADUser -Filter "SamAccountName -eq '$($user.sAMAccountName)'" -SearchBase "DC=subdomain,DC=company,DC=com" -Properties Company | % { Set-ADUser $_ -Replace @{Company = 'Deliveron'} } 7 }

 

If you then wanted to query AD for those users to make sure they updated correctly, you could use the following query using Get-ADUser:

1 foreach ($user in $userList){ 2 Get-ADUser -Filter "SamAccountName -eq '$($user.sAMAccountName)'" -SearchBase "DC=subdomain,DC=company,DC=com" -Properties Company | Select SamAccountName, Name, Company 3 }

Query for User Accounts in Active Directory with PowerShell

by Jess Collicott 24. February 2012 16:51

Occasionally there is a need to quickly query Active Directory for all user accounts or user accounts with only certain values in particular properties. This can be done by installing and loading the Microsoft Active Directory Administration module for PowerShell. This is an add-on module, named ActiveDirectory, that provides cmdlets that let you manage your Active Directory domains.

After you install the ActiveDirectory module, there is now a new PowerShell option in Administrative Tools, called “Active Directory Module for Windows PowerShell”:

screen1

This brings up the bland, DOS-like command prompt with the ActiveDirectory module automatically loaded. But what if you like to work in the Windows PowerShell Integrated Scripting Environment (ISE)? Start up ISE and then run the following command:

Import-module ActiveDirectory

That will load the ActiveDirectory module into your ISE session, so that you can use the desired cmdlets.

Querying for User Accounts

To query for user accounts, use the Get-ADUser cmdlet. For example, here is how you would query against your domain for all user accounts:

Get-ADUser -Filter * -SearchBase "DC=ad,DC=company,DC=com"

If you wanted to query for all of the user accounts with the last name “Collicott”, you would run the following:

Get-ADUser -Filter {Surname -eq "Collicott"} -SearchBase "DC=ad,DC=company,DC=com"

To export the e-mail addresses for all user accounts to a CSV file, you could run the following:

Get-ADUser -Filter * -SearchBase "DC=ad,DC=company,DC=com" -Properties mail | Select mail | Export-CSV "Email Addresses.csv"

You can also find additional examples by viewing the help on the cmdlet:

Get-Help Get-ADUser -examples

Change Settings for “New” Icon in SharePoint 2010 using PowerShell

by Jess Collicott 5. January 2012 19:06

The amount of time the “New” icon is shown in SharePoint 2010 can be changed at the Web Application level using PowerShell. Below are examples to get or change settings for the icon:

Get the Current Duration to Display the “New” Icon

$webApp = Get-SPWebApplication "http://webAppURL/" $webApp.DaysToShowNewIndicator

Change the Duration to Display the “New” Icon

# Set to 1 Day $webApp = Get-SPWebApplication "http://webAppURL/" $webApp.DaysToShowNewIndicator = 1 $webApp.Update()

Prevent the “New” Icon from Displaying

# Essentially, just set the display duration to 0 days. $webApp = Get-SPWebApplication "http://webAppURL/" $webApp.DaysToShowNewIndicator = 0 $webApp.Update()

Executing PowerShell Scripts on Remote Machines with TFS 2010 and Team Deploy 2010

by Mike Douglas 8. December 2010 05:45

Team Deploy 2010 is a custom add-on for Team Foundation Server 2010 (TFS) to deploy MSIs to servers and PCs.  The deploy activity uses an XML file to manage the servers and steps for deployment including starting/stopping services and installing/uninstalling the MSIs.  This is very effective for automated deployments in environments where automated deployments are allowed.  This however does not provide a practice run into downstream environments where automated deployments are not allowed such as Staging/Integration and Production.

An alternative to this that does offer some deployment consistencies beyond the MSI is to have Team Deploy 2010 (or Team Deploy for TFS 2008 also supports this) execute a PowerShell script to perform the deployment steps.  The advantage of this is that the PowerShell scripts can also be used to perform the manual deployments to these other environments.  This won’t work in every scenario but should in a lot.  In this post, I am going to explain how to do this.

The first thing to do is to install Team Deploy 2010.  This is free and can be downloaded at http://TeamDeploy.CodePlex.com.  The installation instructions are detailed on the site.  For this, I will assume Team Deploy 2010 is already installed.

Next open Visual Studio 2010 and create a new build definition workflow.  Create 3 arguments called RemoteExecuteFilename, TargetMachine, and RemoteCommand.

Instead of using the Deploy activity, add the RemoteExecute activity in an AgentScope container.

image

Set the properties on the RemoteExecute activity to the arguments passed in.

image

Next, set the properties that were exposed as arguments of the build definition.  For the RemoteCommand, here is where you want to specify calling PowerShell.exe and the script file that will be executed on the target machine.  One thing I have learned after taking this snapshot is that if you have a space in the path for the script than use this syntax:

PowerShell.exe –File “\\buildserver\deploy scripts\Update.ps1”

Next specify the path where the PSTools were installed and finally specify the machine that you want to run the remote script.

image

The final step is to create the deployment script.  Thanks to the power of PowerShell, these deployment scripts can perform any action.  I have created steps for starting/stoping services, applying SQL Server schema changes, search and replace strings in configuration files, etc. Essentially anything you can do in a batch file and in .NET code, can be done in PowerShell.

Here is a small sample script that I created.  I have creates some much more complicated scripts and ran them on remote machines without any issues.

"Performing removal steps..."

$servicename = "PLA"
$service = Get-Service $servicename
if($service.Status -eq "Running")
{
    "Stopping " + $servicename
    Stop-Service $servicename
}
"status=" + $service.Status
Remove-Item "c:\miketest2"
msiexec /qn /x "{26260DBA-1519-4967-9118-D827793EF3B3}"

"Removal complete.  Starting the installation steps..."

msiexec /qb! /i "\\buildserver\deploy\simple.msi"
New-Item "c:\miketest2" -type directory

"Applying SQL Server Schema changes..."
sqlcmd -S W2K8R2BOOT -E -i \\buildserver\deploy\dropaddcooltable.sql

if($service.Status -eq "Stopped")
{
    "Starting " + $servicename
    Start-Service $servicename
}

This is it. Here are also a couple things to consider. Copy MSIs, SQL Scripts, and the deployment script to a versioned folder.  The folder is the snapshot in time including the deployment file.  Keep the deployment scripts in source control.  Lastly there is a new feature in PowerShell 2.0 called PowerShell Remoting.  I have tried it, but it looks like this could also work.  It is on my list to research and I will be sure to report back when I find out more information.

Enjoy!

Mike

  •   

Converting SHAREPOINT Sub-Sites to Site Collections

by MoeElatta 29. April 2010 07:14

Ever run into that problem where you keep adding webs to a single site collection then realize that your content database is growing to a size beyond belief? The logical next step would be to convert some of these webs to site collections so they can reside on their own content databases. Although this might seem like a difficult task, I will show you how to convert a SharePoint Sub-Site into a Site Collection using the power of PowerShell (PoSH). Windows PowerShell is an extensible automation engine from Microsoft consisting of a command-line shell and associated scripting language. The benefit of performing this conversion is that it allows in a scale-out scenario where each site collection can reside in its own database and potentially scaling-out even further by storing those databases on different physical SQL Servers. This way, the physical storage for site collections can be adjusted with minimal downtime and without affecting the logical URL structure of the site the end-user interacts with.

Install Windows PowerShell 2.0

PowerShell 2.0 is included with Windows 7 and Windows 2008 R2; it can also be downloaded using the following link: http://support.microsoft.com/kb/968929

It is recommended to install PowerShell on the same machine that hosts the SharePoint server. However, PowerShell 2.0 has a remoting feature included that allows execution of scripts against remote machines as long as both machines are on the same domain or added to the TrustedHosts configuration setting.

Launch Windows PowerShell 2.0 ISE

When you install Windows PowerShell the setup program should also install a Start Menu shortcut for you; that shortcut can be found by clicking Start —> All Programs —> Accessories –> Windows PowerShell –> Windows PowerShell ISE.

When you do start Windows PowerShell you’ll see something similar to this:

image

Script for Performing Conversion

The script for performing the conversion has been separated out into four separate scripts. Although multiple commands may be run at once it is recommended to run each command individually in order to view the results returned from each command’s execution.

Script Legend

Red = Environment specific, must be replaced.

Green = Comment

First Script

The main functions of the first script are to rename the current Sub-Site, export its data, create a new Site Collection, and finally import the data into the new Site Collection.

When creating a new site collection ensure that it is being created on a new content database.

There are two ways of accomplishing this task:

1. Create a new content database through Central Administration

2. Use the stsadm createsiteinnewdb command.

Creation of a content database using Central Administration:

http://technet.microsoft.com/en-us/library/cc825314(office.14).aspx

Creation of a content database using the stsadm createsiteinnewdb command: http://technet.microsoft.com/en-us/library/cc262407.aspx

#Declare a variable and set its value to the Sub-Site name that will be converted to the Site Collection.

$filename = "Sub-Site Name"

#Declare a variable and set its value to the fully qualified domain name for the Sub-Site.

$url = "http://www.HostName.com/Sub-Site Name"

#Declare a variable and set its value to the user that’s going to be the Site Collection owner.

$user = "DomainName\UserName"

#Declare a variable that will be used for identifying the Site Collection’s owner e-mail address.

$email = "UserName@DomainName.com"

#Load the SharePoint Assembly to gain access to SharePoint’s object model and be able to execute commands #against SharePoint server.

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

#Declare a variable and set its value to the current site collection using the URL variable declared earlier

$site = new-object microsoft.sharepoint.spsite($url)

#Declare a variable and set its value to the current Sub-Site

$web = $site.OpenWeb()

#Declare a variable and set its value to the Web Template & Web Template ID which gets the name of the site definition #that was used to create the site. This is done because the same site definition will be used for creating the new Site #Collection otherwise some features will have to be activated manually.

$template = "$($web.WebTemplate)#$($web.WebTemplateid)"

#This command exports the site and sub-sites data into to a folder using the filename variable.

stsadm -o export -url "$url" -filename "$filename" -includeusersecurity -versions 4 -nofilecompression -quiet

#This command renames the current site by appending an “_ORIG” to its name.

stsadm -o renameweb -url "$url" -newname "$($filename)_ORIG"

#The addpath command specifies where new site collections can be created by using the URL parameter.

stsadm -o addpath -url "$url" -type explicitinclusion

#Create a site collection at the specified (URL) with the specified user as site collection owner and site collection #administrator and use the same template as the original site.

stsadm -o createsite -url "$url" -owneremail $email -ownerlogin $user -sitetemplate $template

#Import the site and sub-site data into the new site collection using the data file exported earlier.

stsadm -o import -url "$url" -filename "$filename" -includeusersecurity -nofilecompression –quiet

Second Script

Importing the data into the new Site Collection imports all of the groups and users that existed within the original site collection which may contain several groups and users that have no relationship with the newly created site collection. Therefore these groups and users must be removed. The second script takes care of this action.

#Declare a variable and set its value to the current site collection using the URL variable declared earlier

$site = new-object microsoft.sharepoint.spsite $url

#Declare a variable and set its value to the current Sub-Site

$web = $site.OpenWeb()

#Create a new variable and set its value to an empty hash table

$x = @{}

#Add all of the groups associated to all of the sites & sub-sites within the site collection to the (x) hash table.

$site.AllWebs|%{$_.Groups}|select Name,Id -unique |?{$x.Contains($_.Name) -eq $false}|%{$x.Add($_.Name,$_.Id)}

#Create a new variable and set its value to an empty hash table.

$y = @{}

#Iterate through all groups and only add the ones that aren’t associated to the newly created site.

$web.SiteGroups|?{$x.Contains($_.Name) -eq $false}|?{$y.Contains($_.Name) -eq $false}|%{$y.Add($_.Name,$_.Id)}

#Remove the unnecessary groups.

$y.keys|%{$web.SiteGroups.RemoveById($y[$_])}

#Clear both hash tables

$x.Clear()

$y.Clear()

#Add all of the users associated to all of the sites & sub-sites within the site collection to the (x) hash table.

$site.AllWebs|%{$_.Users}|select Name,Id -unique |%{$x.Add($_.Id, $_.Name)}

$web.siteGroups | % {$_.Users} | select name, id -unique |?{$x.Contains($_.Id) -eq $false}| %{$x.Add($_.Id, $_.Name)}

#Iterate through all users and only add the ones that aren’t associated to the newly created site.

$web.SiteUsers|select name, id -unique | ?{$x.Contains($_.Id) -eq $false}|%{$y.Add($_.Id, $_.Name)}

#Remove the unnecessary users.

$y.keys|%{$web.SiteUsers.RemoveById($_)}

New Site Collection Verification

To ensure that the new Site Collection has been created properly browse to both the original and new Site Collection, and cross check these items:

Home page appearance of both sites should be the same.

Verify that unnecessary groups and users have been removed from the new Site Collection

From the home page click on People and Groups –> More…

Compare both lists; the new site collection should have a smaller number of groups.

Comparing the All People lists should yield similar results.

Using the newly created Site Collection, go to the site settings page and verify that the site collection settings section is visible.

Third Script

The final step of this process is to delete the original site and any sub-sites that belong to it. In order to delete a site, any sub-sites must be deleted first. The third script performs this action by creating a function that iterates through the site’s sub-sites and deletes each one before finally deleting the parent site.

#Create a function for deleting all sub-sites.

function delete-all-webs($url)

{

#This is used for display purposes, it prints the current sub-site that’s going to be deleted.

"Delete web {0}" -f $url

#Create an xml object variable and set its value to all sub-sites that have been created #immediately below the site.

[xml]$xwebs = stsadm -o enumsubwebs -url $url

#Iterate through all sub-sites if they exist and delete each one.

if($xwebs.Subwebs.Count -gt 0){

foreach($web in $xwebs.Subwebs.subweb){

#Call the function for any child sub-sites that need to be deleted first.

delete-all-webs -url $web

}

}

#Command that performs the deletion

stsadm -o deleteweb -url $url

}

#Call the function to delete the sub-sites and parent site.

delete-all-webs -url "$($url)_ORIG"

To verify that the original sub-site no longer exists, browse to it using an internet explorer window making sure that the “_ORIG” is appended. If the deletion was performed correctly a “page not found” error should be displayed.