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