Monday, December 28, 2015

Powershell to Get the Public Key token of dll

Powershell to Get the Public Key token of dll:

([system.reflection.assembly]::loadfile("c:\MyDLL.dll")).FullName

Monday, November 30, 2015

Update the PageLayout using PowerShell

Update the PageLayout using PowerShell


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

$web = Get-SPWeb -Identity "http://myDomain.com/authoring/en-us";  #Change web that you're modifying on this line

$spPubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($web);
$pages = $spPubWeb.PagesList;

foreach($item in $pages.Items)
{
  $pubPage = [Microsoft.SharePoint.Publishing.PublishingPage]::GetPublishingPage($item)

  $url = new-object Microsoft.SharePoint.SPFieldUrlValue($pubPage.ListItem[[Microsoft.SharePoint.Publishing.FieldId]::PageLayout].ToString())

  if($url -ne $null)
  {   
    if($url.Url -match 'http://mydomain.com/prod-cat/_catalogs/masterpage/TestPageLayout.aspx')  #Change Page layout name on this line
    {  
      $pubPage.Name
      $pubPage.CheckOut()    
      $pubPage.ListItem[[Microsoft.SharePoint.Publishing.FieldId]::PageLayout] = "http://mydomain.com/_catalogs/masterpage/newPageLayout.aspx"
      $pubPage.ListItem.UpdateOverwriteVersion()
      $pubPage.ListItem.File.CheckIn("Fixed URL to page layout.", [Microsoft.SharePoint.SPCheckinType]::MajorCheckIn);
    }
  }
}

Export the Page Library/list Items to CSV using PowerShell


Export the Page Library/list Items to CSV using PowerShell


$web = Get-SPWeb -identity "http://mydomain.com/site/"

#Get the Target List
$list = $web.Lists["Pages"]

#Array to Hold Result - PSObjects
$ListItemCollection = @()

$list.Items  | foreach {
$ExportItem = New-Object PSObject
$ExportItem | Add-Member -MemberType NoteProperty -name Title -value $_["Title"]
$ExportItem | Add-Member -MemberType NoteProperty -Name Name -value $_["Name"]
$ExportItem | Add-Member -MemberType NoteProperty -name Created -value $_["Created"]
$ExportItem | Add-Member -MemberType NoteProperty -name ExternalURL -value $_["Byline"]


#Add the object with property to an Array
$ListItemCollection += $ExportItem
}
#Export the result Array to CSV file
$ListItemCollection | Export-CSV e:\pub\ExportFile.csv ~ -NoTypeInformation                       

#Dispose the web Object
$web.Dispose()

Update the Document Library Items from one library to another library

Below script is an example for updating the Items from one document library to another document library.

Add-PSSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue 
try
{
   $srcListSiteUrl = "http://mydomain.com/en-us/"
   $SourceListName = "Pages"     
   
   $dstListSiteUrl = "http://mydomain.us.com/en-us/"
   $DestinationListName = "Pages"
   
   $keyColumnInternalName = "FileLeafRef"     
   $sourceListWeb = Get-SPWeb -identity $srcListSiteUrl    
   $sourceListUrl = $sourceListWeb.ServerRelativeUrl + "/" +$SourceListName;     
   $dstListWeb = Get-SPWeb -identity $dstListSiteUrl    
   $destinationListUrl = $dstListWeb.ServerRelativeUrl + "/" + $DestinationListName;
   $SourceList = $sourceListWeb.GetList($sourceListUrl);   
   $DestinationList = $dstListWeb.GetList($destinationListUrl); 

     
   $filterQuery = '<Query>
<OrderBy>
<FieldRef Name = "Title" />
</OrderBy>
</Query>'     
    

$CategoryQuery = new-object Microsoft.SharePoint.SPQuery
$CategoryQuery.Query = $filterQuery

    $sourceSPListItemCollection = $SourceList.GetItems($CategoryQuery);

    foreach($srcListItem in $sourceSPListItemCollection) 
    {           
        $keyValue = $srcListItem[$keyColumnInternalName]

        $camlQuery ='<Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">'+$keyValue+'</Value> </Eq> </Where>'
        $spQuery = new-object Microsoft.SharePoint.SPQuery
        $spQuery.Folder = $DestinationList.RootFolder.SubFolders["Foldername"]
        $spQuery.Query = $camlQuery
        $spQuery.RowLimit = 1
        $destItemCollection = $DestinationList.GetItems($spQuery)
   if($destItemCollection.Count -gt 0)
   {
   foreach($dstListItem in $destItemCollection) 
   {  
                           $url = [String]::Format("{0}{1}",$dstListWeb.Url + "/", $dstListItem.File.Url)
                           $file = $dstListWeb.GetFile($url)
                           $file.CheckOut()
           $fileItem = $file.Item
                           Write-Host $fileItem.Name is updating Please wait ...........

   $fileItem["CustomText"] = $srcListItem["Introduction"]
                            $fileItem["Author"] = $srcListItem["Author"]                
   $fileItem.Update() 
                            $file.CheckIn("Updated Value")
            $file.Publish("Publish through Powershell")
                    } 
   }        
    }
}
catch 
    write-host $_.exception 
finally 
{        
    if($sourceListWeb -ne $null){$sourceListWeb.Dispose()}
    if($dstListWeb -ne $null){$dstListWeb.Dispose()}
}

Update the Document library item from CSV using PowerShell

Below script will update a particular item in the page library. In this example the created date will be updated from the source csv, if the filename matches in both CSV and the page library

if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) { 
Add-PSSnapin "Microsoft.SharePoint.PowerShell" 

$web = get-spweb http://mydomain.com/authoring
$list = $web.Lists["Pages"] -as [Microsoft.SharePoint.SPDocumentLibrary]

$delimeter = "~"
$filePath = "C:\source.csv"
$exceldatas = Import-Csv $filePath -Delimiter $delimeter
$cnt = 0
foreach ($item in $list.Items)
{
    $url = [String]::Format("{0}{1}",$web.Url + "/", $item.File.Url)
    $file = $web.GetFile($url)   
    foreach($exceldata in $exceldatas) 
If($item.Name -eq $exceldata.Name)
$file.CheckOut()
$fileItem = $file.Item
$fileItem["Created"] = $exceldata.Created
$fileItem.Update()
$file.CheckIn("Updated Created Date")
$file.Publish("Publish through Powershell")
$cnt = $cnt + 1
Write-Host "Please wait item " $item.Name " is getting updated...."
}
    }
}
Write-Host "Update compelted for " $cnt " Items....."

Thursday, October 1, 2015

SPQuery Using Multiple AND OR Operators

Scenario 1

Get me all items in a list WHERE fullName equals the currently logged in user.
1
2
3
4
5
6
7
8
9
10
11
SPWeb web = SPControl.GetContextWeb(Context);
 
string fullName = web.CurrentUser.Name;
 
SPQuery oQuery = new SPQuery();
 
oQuery.Query = 
    "<Where>" + 
    "<Eq><FieldRef Name='FullName'/><Value Type='Text'>'" + fullName + "'</Value></Eq>" + 
    "</Where>" +
    "<OrderBy><FieldRef Name='StartTime' Ascending='FALSE'></FieldRef></OrderBy>";

Scenario 2

Get me all items in a list WHERE fullName equals the currently logged in user AND status equals ‘Complete’.
1
2
3
4
5
6
7
8
9
10
11
12
13
SPWeb web = SPControl.GetContextWeb(Context);
 
string fullName = web.CurrentUser.Name;
 
SPQuery oQuery = new SPQuery();
oQuery.Query = 
    "<Where>" +
    "<And>" +
        "<Eq><FieldRef Name='FullName'/><Value Type='Text'>'" + fullName + "'</Value></Eq>" +
        "<Eq><FieldRef Name='Status'/><Value Type='Text'>Complete</Value></Eq>" + 
    "</And>" +
    "</Where>" +
    "<OrderBy><FieldRef Name='StartTime' Ascending='FALSE'></FieldRef></OrderBy>";

Scenario 3

Get me all items in a list WHERE fullName equals the currently logged in user AND status equals ‘Complete’ AND manager is James Lane.
This is where it gets a bit tricky. The following example is INCORRECT and will produce an error when run:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
SPWeb web = SPControl.GetContextWeb(Context);
 
string fullName = web.CurrentUser.Name;
 
SPQuery oQuery = new SPQuery();
oQuery.Query = 
    "<Where>" +
    "<And>" +
        "<Eq><FieldRef Name='FullName'/><Value Type='Text'>'" + fullName + "'</Value></Eq>" +
        "<Eq><FieldRef Name='Status'/><Value Type='Text'>Complete</Value></Eq>" +
        "<Eq><FieldRef Name='Manager'/><Value Type='Text'>James Lane</Value></Eq>" +
    "</And>" +
    "</Where>" +
    "<OrderBy><FieldRef Name='StartTime' Ascending='FALSE'></FieldRef></OrderBy>";
This is the correct way to do it:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
SPWeb web = SPControl.GetContextWeb(Context);
 
string fullName = web.CurrentUser.Name;
 
SPQuery oQuery = new SPQuery();
oQuery.Query = 
    "<Where>" +
    "<And>" +
        "<And>" +
            "<Eq><FieldRef Name='FullName'/><Value Type='Text'>'" + fullName + "'</Value></Eq>" +
            "<Eq><FieldRef Name='Status'/><Value Type='Text'>Complete</Value></Eq>" +
        "</And>" +
        "<Eq><FieldRef Name='Manager'/><Value Type='Text'>James Lane</Value></Eq>" +
    "</And>" +
    "</Where>" +
    "<OrderBy><FieldRef Name='StartTime' Ascending='FALSE'></FieldRef></OrderBy>";

Scenario 4

Get me all items WHERE fullName equals the currently logged in user AND status equals ‘Complete’ OR status equals ‘On Hold’.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
SPWeb web = SPControl.GetContextWeb(Context);
 
string fullName = web.CurrentUser.Name;
 
SPQuery oQuery = new SPQuery();
oQuery.Query = 
    "<Where>" +
    "<And>" +
        "<Eq><FieldRef Name='FullName'/><Value Type='Text'>'" + fullName + "'</Value></Eq>" +
        "<Or>" +
            "<Eq><FieldRef Name='Status'/><Value Type='Text'>Complete</Value></Eq>" +
            "<Eq><FieldRef Name='Status'/><Value Type='Text'>On Hold</Value></Eq>" +
        "</Or>" +
    "</And>" +
    "</Where>" +
    "<OrderBy><FieldRef Name='StartTime' Ascending='FALSE'></FieldRef></OrderBy>";

Thursday, July 9, 2015

How to create, update and delete a property bag for a site collection.

###############################################################################################
# This script allows to work with SharePoint property bags at the Site Collection Level 
# Required Parameters:  
#    ->$sSiteCollection: Site Collection where we want to do add a property bag. 
#    ->$sOperationType: Operation type to be done with the property bag - Create - Update - Delete. 
#    ->$sPropertyBagKey: Key for the property bag to be added. 
#    ->$sPropertyBagValue: Value for the property bag addded. 
###############################################################################################
 
If ((Get-PSSnapIn -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )  
{ Add-PSSnapIn -Name Microsoft.SharePoint.PowerShell } 
 
$host.Runspace.ThreadOptions = "ReuseThread" 
 
#Definition of the function that allows to create, update and remove a property bag 
function WorkWithSiteCollectionPropertyBags 
{ 
    param ($sSiteCollection,$sOperationType,$sPropertyBagKey,$sPropertyBagValue) 
    try 
    { 
        $spSite=Get-SPSite -Identity $sSiteCollection 
        $spwWeb=$spSite.OpenWeb() 
        switch ($sOperationType)  
        {  
        "Create" { 
            Write-Host "Adding property bag $sPropertyBagKey to $sSiteCollection !!" -ForegroundColor Green                         
            $spwWeb.AllProperties.Add($sPropertyBagKey,$sPropertyBagValue)            
            $spwWeb.Update()             
            $sPropertyBag=$spwWeb.AllProperties[$sPropertyBagKey] 
            Write-Host "Property bag $sPropertyBagKey has the value $sPropertyBag" -ForegroundColor Green 
            }  
        "Read" { 
            Write-Host "Reading property bag $sPropertyBagKey" -ForegroundColor Green                  
            $sPropertyBag=$spwWeb.AllProperties[$sPropertyBagKey] 
            Write-Host "Property bag $sPropertyBagKey has the value $sPropertyBag" -ForegroundColor Green 
            } 
        "Update" { 
            $sPropertyBag=$spwWeb.AllProperties[$sPropertyBagKey] 
            Write-Host "Property bag $sPropertyBagKey has the value $sPropertyBag" -ForegroundColor Green         
            Write-Host "Updating property bag $sPropertyBagKey for $sSiteCollection" -ForegroundColor Green             
            $spwWeb.AllProperties[$sPropertyBagKey]="SPSiteColPBagUpdatedValue_2"                         
            $sPropertyBag=$spwWeb.AllProperties[$sPropertyBagKey] 
            Write-Host "Property bag $sPropertyBagKey has the value $sPropertyBag" -ForegroundColor Green 
            }  
        "Delete" { 
            Write-Host "Deleting property bag $sPropertyBagKey" -ForegroundColor Green                                     
            $spwWeb.AllProperties.Remove($sPropertyBagKey)             
            $spwWeb.Update()             
            $sPropertyBag=$spwWeb.AllProperties[$sPropertyBagKey] 
            Write-Host "Property bag $sPropertyBagKey has the value $sPropertyBag" -ForegroundColor Green                 
            }            
        default { 
            Write-Host "Requested Operation not valid!!" -ForegroundColor DarkBlue             
            } 
        } 
        $spwWeb.Dispose() 
        $spSite.Dispose() 
    } 
    catch [System.Exception] 
    { 
        write-host -f red $_.Exception.ToString() 
    } 
} 
 
Start-SPAssignment –Global 
#Calling the function 
$sSiteCollection="http://<YourSiteCollection>" 
$sPropertyBagKey="SPSiteColPBagKey_2" 
$sPropertyBagValue="SPSiteColPBagValue_2" 
#WorkWithSiteCollectionPropertyBags -sSiteCollection $sSiteCollection -sOperationType "Delete" -sPropertyBagKey $sPropertyBagKey -sPropertyBagValue $sPropertyBagValue 
WorkWithSiteCollectionPropertyBags -sSiteCollection $sSiteCollection -sOperationType "Create" -sPropertyBagKey $sPropertyBagKey -sPropertyBagValue $sPropertyBagValue 
WorkWithSiteCollectionPropertyBags -sSiteCollection $sSiteCollection -sOperationType "Read" -sPropertyBagKey $sPropertyBagKey -sPropertyBagValue $sPropertyBagValue 
WorkWithSiteCollectionPropertyBags -sSiteCollection $sSiteCollection -sOperationType "Update" -sPropertyBagKey $sPropertyBagKey -sPropertyBagValue $sPropertyBagValue 
WorkWithSiteCollectionPropertyBags -sSiteCollection $sSiteCollection -sOperationType "Delete" -sPropertyBagKey $sPropertyBagKey -sPropertyBagValue $sPropertyBagValue 
 
 
Stop-SPAssignment –Global 
 
Remove-PSSnapin Microsoft.SharePoint.PowerShell

Wednesday, June 3, 2015

Powershell Script to delete sites and the corresponding sub-sites:

Powershell Script to delete sites and the corresponding sub-sites:

if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
    Add-PSSnapin Microsoft.SharePoint.Powershell
}


function RemoveSPWebRecursively(
    [Microsoft.SharePoint.SPWeb] $web)
{
    Write-Debug "Removing site ($($web.Url))..."
    
    $subwebs = $web.GetSubwebsForCurrentUser()
    
    foreach($subweb in $subwebs)
    {
        RemoveSPWebRecursively($subweb)
        $subweb.Dispose()
    }
    
    $DebugPreference = "SilentlyContinue"
    Remove-SPWeb $web -Confirm:$false
    $DebugPreference = "Continue"
}

$DebugPreference = "SilentlyContinue"
$web = Get-SPWeb "http://sitURL/Authoring/en-us"
$DebugPreference = "Continue"

If ($web -ne $null)
{
    RemoveSPWebRecursively $web
    $web.Dispose()
}

Monday, April 6, 2015

Getting public key token for a dll using PowerShell Script


Getting public key token for a dll using PowerShell Script:

([system.reflection.assembly]::loadfile("C:\Windows\Microsoft.NET\assembly\GAC_MSIL\GroupDropDownList\v4.0_1.0.0.0__22c2902360f8dd14\GroupDropDownList.dll")).FullName

It will give the result as:
GroupDropDownList, Version=1.0.0.0, Culture=neutral, PublicKeyToken=22c2902360f8dd14

Monday, February 16, 2015

Managed Metadata changes not applied to list items after changing the term Store Label

Problem:

Managed Metadata changes not applied to list items after changing the term Store Label. 

Sometimes you changed a term and you are wondering why the changed term cannot be seen in a List where you are using the terms in a column.

Consider the following scenario:
·   You are using Managed Metadata and administrate that within the central administration website.
·   You are using a List in a site and added a column to use Terms saved in the Managed Metadata database.
·   You changed a term in the taxonomy term store.
·   You may run manually the Taxonomy Update Scheduler job on the Scheduled Jobs central admin page or waited more than one hour; because the schedule of that job is set out of the box to run every hour.
·   You may see that the changed term has not been updated to the new value on the List where you are using those information.
·   You found the following entry in the ULS log:
·   Exception with ULS log entry:

Exception occurred while hidden list being updated: System.IO.FileNotFoundException: The site with the id 6c03a437-0d6d-44a3-a542-6235b854a36e could not be found.   
at Microsoft.SharePoint.SPSite..ctor(Guid id, SPFarm farm, SPUrlZone zone, SPUserToken userToken)   
at Microsoft.SharePoint.SPSite..ctor(Guid id)   
at Microsoft.SharePoint.Taxonomy.UpdateHiddenListJobDefinition.ProcessProxy(MetadataWebServiceApplicationProxy proxy)   
at Microsoft.SharePoint.Taxonomy.UpdateHiddenListJobDefinition.Execute(Guid targetInstanceId) 

Workaround:
To work around the issue and update the Taxonomy Hidden list manually you can use the following PowerShell script as follows.

Add-PSSnapin microsoft.sharepoint.powershell
$site=Get-SPSite <Site-URL>
[Microsoft.SharePoint.Taxonomy.TaxonomySession]::SyncHiddenList($site)
$site.dispose()

Thursday, February 12, 2015

Updating the User Profile Properties value by reading it from csv

Updating the User Profile Properties value by reading it from csv file:

The below script will read the username & update property from the csv file and update the user profile.

if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
  Add-PSSnapin Microsoft.SharePoint.PowerShell
}

$csvfile="c:\Temp\UserList.csv"
$mySiteUrl = "http://SiteURL"
$upAttribute = "Location"
$upUserName = "UserName"
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
$csvData = Import-Csv $csvfile
foreach ($line in $csvData)
{
       if ($profileManager.UserExists($line.UserName))
       {
              $up = $profileManager.GetUserProfile($line.UserName)
              $up[$upUserName].Value + "|" + $up[$upAttribute].Value | out-file -filepath C:\temp\Before_UserUpdate.txt -append -width 200
              $up[$upAttribute].Value = $line.Location
              $up.Commit()
              $up[$upUserName].Value + "|" + $up[$upAttribute].Value | out-file -filepath C:\temp\After_UserUpdate.txt -append -width 200
             
        }
       else
       {
              $line.username | out-file -filepath C:\temp\UserNotFound.txt -append -width 200

        }
}

$site.Dispose()