Friday, May 17, 2013

SharePoint Powershell Create a new list with different column types

Scenario:
Murali ( my collegue ) was looking for a quick script to create a list using PS with diff columns types.

Solution:
PS - Love it - Google + little brain - recipe ready

Code:

clear
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell
 
try 
{
 
$TestSiteUrl = "http://extranet.contoso.com" #provide site url in this variable
 
$ListName = "KPIConfigList"   #listName

$ListDescription = "KPI config list" #list description
 
$myTestWeb = Get-SPWeb -identity $TestSiteUrl   #Get web object
 
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::GenericList  #GenericList template
 
write-host "Adding list" $ListName
 

$myCustomList = $myTestWeb.Lists[$ListName]
 
if($myCustomList -eq $null) 
{
 
  $lstId = $myTestWeb.Lists.Add($ListName,$ListDescription,$listTemplate)
 
  $myCustomList = $myTestWeb.Lists[$ListName]
 
    #Add columns
 
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Text 

    $myCustomList.Fields.Add("TextField",$spFieldType,$false)

   #Add columns    
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Number 

    $myCustomList.Fields.Add("Order",$spFieldType,$false)

   #Add columns
    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Boolean 

    $myCustomList.Fields.Add("IsDefault",$spFieldType,$false)

   #Add columns
    $choices = New-Object System.Collections.Specialized.StringCollection 

    $choices.Add("Client") 

    $choices.Add("Unit")

    $spFieldType = [Microsoft.SharePoint.SPFieldType]::Choice 

    $myCustomList.Fields.Add("Type",$spFieldType,$false,$false,$choices) 
     
    #Update
    $myCustomList.Update()
 
 write-host "List created successfully" $ListName
 
}
 
else
{ 
  write-host "List already exists" $ListName 
} 
}
 
catch
{ 
  write-host "Error" $_.exception
 
  $errorlabel = $true
 
}
 
finally
{
 
  if($myTestWeb -ne $null)
 {$myTestWeb.Dispose()}
 
  if($errorlabel -eq $true){exit 1}
 
  else {exit 0}
 
}exit 0
Article:
Other column types
Powershell

Friday, March 8, 2013

SharePoint test user creation

Scenario:
We often need local test users, need to be created in Active Directory and also get them added to SharePoint site.

Solution:
Though of sharing what I use :)

Code:

clear

$user = "test.user1"
$userWithDomain = "contoso\"+$user

Import-Module activedirectory
New-ADUser -Name $user -AccountPassword (ConvertTo-SecureString "somepass" -AsPlainText -force) -Enabled $True -PasswordNeverExpires $True -PassThru 


Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

New-SPUser -UserAlias $userWithDomain -Web http://sp2010 -Group "Team Owners"

Thursday, February 7, 2013

Powershell Test Data for Record Center

Scenario:
Wanted to do a load test on Record Center with my custom solution. I wanted to have 100 record libraries with 100 folder each.

Solution:
Powershell script can do it in few minutes

Code:

clear
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

[Void][System.Diagnostics.Stopwatch] $sw;
# New Stopwatch object
$sw = New-Object System.Diagnostics.StopWatch;
# Stop any watches that might be running
$sw.Stop();                                         
$sw.Start();

# Initialization
$webUrl = 'http://recordcenter'
$libCount = 1;
$folderCount = 1;
$libraryName = "Record Library" + $libCount
$frontSlash = "/"
$web = Get-SPWeb $webUrl;
$listTemplate = $web.ListTemplates | Where-Object {$_.Name -eq "Record Library"}
#Create folders 
(1..100)|%{
      $libraryName = "Contract Library" + $libCount                         
      write-host "Creating Record library: " $libraryName                                      
      $web.Lists.Add($libraryName,"Record Library",$listTemplate);
       $libCount  = $libCount + 1;
       [string]$howlong0 = $sw.Elapsed.ToString();  # How long
       Write-Host "Library Ready (Time ): " $howlong0 -F Green;
        $spDocumentLibrary = $web.Lists.TryGetList($libraryName)
                    (1..1000)|%{
                    write-host "Adding Folder in library: " $libraryName
                    $folderName = "Folder" + $folderCount
                 $spFolder = $spDocumentLibrary.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder,$folderName) 
                 $spFolder.Update()
                    $folderCount = $folderCount+1
                   [string]$howlong0 = $sw.Elapsed.ToString();  # How long
                    Write-Host "Folder Ready (Time ): " $howlong0 -F Green;
                    }
}

$web.Dispose()
$sw.Stop();    # Stop the timer
[string]$howlong = $sw.Elapsed.ToString();   # How long
write-host "Done (Time ): " $howlong -F Green;

Sunday, February 3, 2013

SharePoint popup how to

Scenario:
I planned to use SharePoint popup in client project.

Solution:
I did a quick POC and here's what you need to do to make it work.

What goes in Parent Window Header ?
Add following JavaScript in the header section :

function OpenMyWebPage(popupTitle, popupUrl) {
        var options = {
            url: popupUrl,
            autoSize: true,
            showClose: true,
            title: popupTitle,
            dialogReturnValueCallback: function (dialogResult) {
                if (dialogResult == SP.UI.DialogResult.OK) {
                    window.document.location.reload(true);
                }
            }
        };
        SP.UI.ModalDialog.showModalDialog(options);
    }
How to launch the Popup
Edit
What goes in Popup Window - Save button at the end ( to refresh the parent window )
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
           Context.Response.Flush();
           Context.Response.End();
What goes in Popup Window - Cancel button
Nothing is needed here
Hidding Ribbon - Add at the end , in case you dont want to display ribbon

Saturday, January 26, 2013

Power-shell to check-in files

Scenario:
During bulk migration, lot of files left checked out because of lack of metadata. We wanted to check-in all these files. Also we want to restrict the script to only "Record Libraries" in record center.

Solution:
Power-shell

Code:

Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

$rand = new-object System.Random

function CheckInDocument([string]$url)
{

$spWeb = Get-SPWeb $url
$SPBaseTypeDocumentLibrary = [Microsoft.SharePoint.SPBaseType]::DocumentLibrary
$lists = $spWeb.GetListsOfType($SPBaseTypeDocumentLibrary);

foreach ($list in $lists)
{
    if ($list.Hidden -eq $False -and $list.BaseTemplate.ToString() -eq "1302")
    {
        Write-Host Checking in documents from Library : $list.Title
        $getFolder = $spWeb.GetFolder($list.Title)
        $files = $list.CheckedOutFiles

        write-host "Total Checked Out Files : " $files.Count

        $list.CheckedOutFiles | Where { $_.CheckOutStatus -ne "None" } |
        ForEach {
            $_.TakeOverCheckOut();
            #$docItem = $list.GetItemById($_.ListItemId);
            #$docItem["Field To Update"] = "Some value";
            $docItem.SystemUpdate();                    
            $docItem.File.CheckIn("Checked In By Administrator");
            Write-Host "$($docItem.File.Name) Checked In" -ForeGroundColor Green

            }
    }
}

$spWeb.Dispose()


}

CheckInDocument http://sp2010
Article:

Refresh GAC using Powershell

Scenario:
Refreshing GAC is always a painful thing.
Do IISReset / remove old stuff / put new one. Can we automate it ?

Solution:
Certainly.. mighty power-shell can do it easily

If you are running on new machine - you might need to relax executing policy

Set-ExecutionPolicy Unrestricted
Code:
iisreset /stop

Set-Alias Gacutil "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe"

Gacutil /uf EntLibContrib.Data.OdpNet
Gacutil /i "MS ENT dlls\EntLibContrib.Data.OdpNet.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Caching
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Caching.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Common
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Common.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Data
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Data.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Logging
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Logging.dll"

Gacutil /uf Microsoft.Practices.ServiceLocation
Gacutil /i "MS ENT dlls\Microsoft.Practices.ServiceLocation.dll"

Gacutil /uf Microsoft.Practices.Unity.Configuration
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Configuration.dll"

Gacutil /uf Microsoft.Practices.Unity
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.dll" 

Gacutil /uf Microsoft.Practices.Unity.Interception.Configuration
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Interception.Configuration.dll"

Gacutil /uf Microsoft.Practices.Unity.Interception
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Interception.dll" 

Gacutil /uf Telerik.Web.Design
Gacutil /i "Telerik.Web.Design.dll"

Gacutil /uf Telerik.Web.UI
Gacutil /i "Telerik\Telerik.Web.UI.dll" 

Gacutil /uf Telerik.Reporting
Gacutil /i "Telerik\Telerik.Reporting.dll"

Gacutil /uf Telerik.Web.UI.Skins
Gacutil /i "Telerik\Telerik.Web.UI.Skins.dll"

iisreset /start

Tuesday, January 15, 2013

Event receiver with Elevated Privileged

Scenario:
Client wanted to run the event receiver code with elevated access.

Solution:
Using Elevated Privileged is one option but better options was using System User Token
Code:

/// 
        /// An item is being added.
        /// 
        public override void ItemAdding(SPItemEventProperties properties)
        {
            SPSite site = properties.Web.Site;
            SPUserToken sysToken = site.SystemAccount.UserToken;
            site.Dispose();

            using (var systemSite = new SPSite(properties.SiteId, sysToken))
            {
                using (SPWeb sysWeb = systemSite.OpenWeb(properties.Web.ID))
                {
                       // Code goes here 
                }
            }