Thursday, February 12, 2015

Powershell to update multiple items with specific condition

Scenario:
Client wanted to restructure the data and wanted to update all the items in a list with particular value to a new value.

Solution:
Quick PS script did the magic

Code:

cls

#Load SharePoint Snap In
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function xUpdateAll-SPItems
{  
 param ($Url, $ListName,$ColumnName,$OldValue,$NewValue) 

$web = Get-SPWeb $Url 
$list = $web.Lists.TryGetList($ListName)

$items = $list.Items
foreach ($item in $items)
{
    $existingValue  = $item[$ColumnName]
    If($existingValue -eq $OldValue)
    {  
       Write-Host "Updating item : " + $item.ID      
     
        $item[$ColumnName] = $NewValue
        $item.Update()     
     }     
}  

 $web.Dispose()
 Write-Host "Updated all items successfully" -foregroundcolor Green  
 
}


#$url=Read-Host "Enter site url"
#$listName=Read-Host "Enter list library name"
#$columnName=Read-Host "Enter column name"
#$oldValue=Read-Host "Enter old value"
#$newValue=Read-Host "Enter new value"

$url="http://server:37788"
$listName="mylist"
$columnName="Column Name"
$oldValue="Bad Value"
$newValue="Other"


xUpdateAll-SPItems $url $listName $columnName $oldValue $newValue

Article:

Tuesday, May 27, 2014

Search display templates not present on site collection

Scenario:
When you configure a Search Result via CA, you might see the following error in the Preview panel:

The Search display templates are not present on this site collection. To add them, you need to activate the "Search Server Web Parts and Templates" feature on the Site Collection Features page.

Solution:
Open up the SharePoint 2013 Management Shell as Administrator and run the following command:

Enable-SPFeature SearchWebParts -url http://central_admin_url

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: