When creating a SharePoint development environment you eventually need to create data to work , such as Sites, Documents Libraries, Users, etc. Creating a Site Collection and a couple of sites is pretty easy and fast, but creating other data like Active Directory users or documents to upload is a little bit more time consuming. To help with these arduous tasks we can use PowerShell.

The following scripts are some examples of the type of data we can create so we can start working quickly. We will create Active Directory users, a Site structure and some Office files that we can also upload.

To create PowerShell scripts I like to use PowerGui (http://www.powergui.org) which is a great tool, but PowerShell ISE that gets installed in Windows Server or Windows 7 is also very good.

Creating Active Directory Users

The first step is to create Active Directory users that we can use in our SharePoint development environment. For this task we will use the Active Directory Powershell Module that comes with Server 2008 R2 or above. Here is the reference to the module. http://technet.microsoft.com/en-us/library/dd378937(WS.10).aspx

To create a couple of users, we can just make up the names, but when we want a bigger list to create at once, we can use one of the multiple sites that create lists of fictitious names that we can use. For this example I am using this Site, which will let you download a list of names in a CSV format, which we can use as a starting point to create the file we can import to the PowerShell script.

The data in the CSV file we need follows this format:

FirstName,MiddleInitial,LastName,Department,JobTitle,LogonName, Password,City,EmailAddress,Phone,Manager,ADGroup
Juan,I,Rangel, Consulting,Analyst,JuanRangel,Password!,London,JuanRangel@domain.com,966 580 628,,SPContributors
Ann,B,Thompson, Finance,Analyst,AnnThompson,Password!,New York,AnnThompson@domain.com,405-558-7328,JuanRangel,SPReaders

The fields that need some attention are Password , that need to follow the password rules in the Active Directory you are using and the Manager that need to be the LogonName of an existing user, so we need to make sure the names on the top of the file are managers so they will be created before non-managers.

First of all, we will create an Organizational Unit (OU) if it doesn’t exists

    Get-ADOrganizationalUnit $OU
    New-ADOrganizationalUnit -Name "SPUsers" -Path $($ou.Substring($ou.IndexOf(',')+1)) -ProtectedFromAccidentalDeletion $false

And then, import the csv and create all the users

Import-Csv $CSVPath | ForEach-Object -Process {
        $displayName = $_.FirstName +" "+ $_.LastName
        $sam = $_.LogonName
        $firstName = $_.FirstName
        $initials = $_.MiddleInitial
        $lastName = $_.LastName
        $email = $_.EmailAddress
        $department = $_.Department
        $title = $_.JobTitle
        $city = $_.City
        $phone = $_.Phone
        $accountPassword = $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
        $manager = $_.Manager
        $ADGroup = $_.ADGroup
New-ADUser -Name $displayName -DisplayName $displayName -SamAccountName $sam -GivenName $firstName -Initials $initials -Surname $lastName -EmailAddress $email -Department $department -Title $title -City $city -OfficePhone $phone -AccountPassword $accountPassword -Enabled:$true
$newUser = (Get-ADUser $sam).DistinguishedName
if($ADGroup -ne ""){
                Get-ADGroup $ADGroup
                New-ADGroup -Name $ADGroup -GroupScope 1 -Path $OU
                Add-ADGroupMember -Identity $ADGroup -Members $newUser
        Move-ADObject -Identity $newUser -TargetPath $OU
        #Set Manager Field
        if($manager)        {
            try {
                $userExists = Get-ADUser -Identity $manager 
            } catch { }
                Get-ADUser -Identity $sam | Set-ADUser -Manager $manager

Note that this script creates the users and groups in Active Directory but does nothing to add those users to SharePoint.

Create Files

On any SharePoint implementation, the most common content are mostly Office documents, and we can automate the creation of these documents with PowerShell.

For this task, we will need Office installed where we are running the script since it uses office Com Objects. Similar to the previous example, we are going to create a CSV file that contains the basic information to create the documents, such as the name and some content.

The CSV follows this structure:

docx,Word Document 1,This is the content for the document 1
txt,Text Documen 2,This is the content for the text document 2
xlsx,Excel file 3,This is the content for the Excel document 3

With this example, we are just creating Word, Excel or Text documents, but you can expand it to other formats if required. The code is pretty self-explanatory as it gets the data from the CSV file and creates the documents with some basic content, on a specified directory.

Import-csv $CSVPath | foreach-object -Process {
        $fileFormat = $_.Format
        $fileName = $_.Name
        $fileContent = $_.Content
        $file = $OutputPath + $fileName + "." + $fileFormat   
                [ref]$SaveFormat = "microsoft.office.interop.word.WdSaveFormat" -as [type] 
                $word = New-Object -ComObject "Word.application"            
                $word.visible = $false            
                $doc = $word.Documents.Add()            
                $word.Selection.Font.Size = "15"            
                $word.Selection.Font.Size = "10"            
                $excel = New-Object -ComObject "Excel.application"            
                $excel.visible = $false            
                $doc = $excel.workbooks.Add()            
                $sheet = $doc.WorkSheets.Item(1)
                $sheet.Cells.Item(1,1) = $fileName  
                $sheet.Cells.Item(1,1).Font.Size = "15"
                $sheet.Cells.Item(2,1) = $fileContent  
                $sheet.Cells.Item(2,1).Font.Size = "10"                                        
                $fileContent | out-file -FilePath ($OutputPath + $fileName + "." + "txt")


Next step is to be able to upload the documents on some sites that we also will create using PowerShell.

Create a Site Structure

Similar to the previous scripts, we will use a CSV file to get all the information needed to create the sites. The file follows this structure:

http://sp,/,site 10,site10,STS#0
http://sp,/site10,site 20,site20,STS#0
http://sp,/,Blog 10,blog10,BLOG#0

Where SiteCollection is the absolute SiteCollection URL, and ParentSiteURL and SiteURLs are the RELATIVE URLs. To create a site on the Site Collection root, enter the ParentSite as "/", like the first and third rows in the example.

The example above creates 3 sites: the first on http://sp/site10 using Team Site template, a second on http://sp/site10/site20 using the same template and a third one http://sp/blog10 using the Blog Site Template

When creating hierarchies, make sure the parent site row precedes any of its children.


Import-Csv -Path $CSVPath | ForEach-Object -Process {
        $siteCollection = $_.SiteCollection
        $parentSiteUrl = $_.ParentSiteUrl
        $siteName = $_.SiteName
        $siteUrl = $_.SiteUrl
        $siteTemplate = $_.SiteTemplate
        $parentSite = Get-SPSite -Identity $siteCollection
        $spweb = $parentSite.OpenWeb($parentSiteUrl);
        $newUrl = $spweb.Url + "/" + $siteUrl
        $newWeb = $spweb.Webs.Add($siteUrl,$siteName,$siteName,[int]1033,$siteTemplate,$false,$false)
        Write-Host $newWeb.Url

Upload Documents

The last task will be uploading the documents we created earlier to the sites. Again, we are going to use a CSV file to get the configuration about what documents are going where. The structure for the CSV file is the following:

http://dc,Shared Documents,Word Document 1.txt

And the code,


Import-Csv -Path $CSVPath | ForEach-Object -Process {
        $WebURL = $_.WebUrl
        $DocLibName = $_.DocLibName
        $FileName = $_.FileName
        $FilePath = $DocsFolder + "\" + $FileName
        #Get the Web & Lists to upload the file 
        $Web = Get-SPWeb $WebURL
        $List = $Web.GetFolder($DocLibName)  
        #Get the Files collection  
        $Files = $List.Files  
        #delete the File from library, if already exist!
        if($Files.Item($DocLibName +"/" + $FileName)) 
            $f=$Files.Item($DocLibName +"/" + $FileName)
            if($f.level -ne "Checkout")
        #Get the File 
        $File = Get-ChildItem $FilePath
        #Add File to the collection 
        $f=$Files.Add($DocLibName +"/" + $FileName,$File.OpenRead(),$true)
        $f.CheckIn("File Added")
        #Dispose the objects 

These scripts are just a starting point to create your own to load a base line of data to a SharePoint Development environment, and you can create other types of data, like lists and fill them up with more information.

You can download the PowerShell module that contains the functions and some basic help. Just drop it in your personal Powershell Modules folder, import it and is ready to use.