Monday, March 26, 2012

Upload Douments in Document Library Sharepoint 2010

I needed to make some tests on Sharepoint Tresholds, so I needed a small script that uploads a large amount of documents (The same document) in my Doc Libraries.
For that I just created in the same folder where my Powershell script is running a small Test.txt file. And Uploaded it a given number of times under a new name.
Here's the script:

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

$uploadURL = "http://MYWEBURL/"
$fileName = "test.txt"
$uploadLibraries = @("Documents", "Documents2")
#I'm Uploading to the root, but you could put there a folder like "Documents/FolderName"
#I want to uplaod 6000 docs on each library... that takes a while
$TOTALDOCSTOUPLOAD =6000
$startFileIndex = 0
$thisScriptPath = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$oldFilePath =  $thisScriptPath + "\" + $fileName
                   
$site = Get-SPSite -Identity $uploadURL
if($site -ne $null){
    $web = $site.OpenWeb()
      if($web -ne $null -and $web.Exists){
        foreach($uploadLibrary in $uploadLibraries)
        {
            try
            {
                $docLib = $web.GetFolder("/"+$uploadLibrary)
            }
       
            catch
            {
               write-host 'Document  Library is unavailable'
                $docLib = $null
            }
            for($i = $startFileIndex; $i -lt $TOTALDOCSTOUPLOAD; $i++)
            {
                if($docLib -ne $null)
                {
                    $fileParts = $fileName.split(".")
                    $fileParts[0] = $fileParts[0]+ $i.ToString()
                    $newFileName = [string]::join('.', $fileParts)
               
                    $newFilePath =  $thisScriptPath + "\" + $newFileName
                   
                    Rename-Item $oldFilePath $newFilePath
                    $docUrl = $docLib.ServerRelativeUrl + "/" + $newFileName
                    if($docLib.Files[$docurl].Exists)
                    {
                        $file = $docLib.Files[$docurl]
                        if($file.LockType -eq "None" -and $docLib.RequiresCheckout)
                        {
                                $file.CheckOut()
                        }
                    }
                    $fileStream =$((Get-ChildItem $newFilePath).OpenRead())
                    $docLib.Files.Add($docUrl, $fileStream, $true) | Out-Null
                    $file = $docLib.Files[$docurl]
                    if($file.CheckOutType -ne "None")
                    {
                       if($docLib.RequiresCheckout) {
                        $file.CheckIn("Updated Template", 1)
                        }
                    }
                    $fileStream.Dispose()
                    Rename-Item  $newFilePath $oldFilePath
                    write-Host "Uploade "$newFilePath "to "$uploadLibrary
                }
             }  
        }

        $web.Update()
        $web.Dispose()
    }
    $site.Dispose()
}


Wednesday, March 7, 2012

Enabling / Adding Sharepoint Search Autocompletion

Ever wonder how to get that Auto-completion to work on the SharePoint search box?


Select the Service application:

$srchSvcApp = Get-SPEnterpriseSearchServiceapplication -Identity "Search Service Application"

Add a new Suggestion:

$lang = "de-de"
$newQuerySuggestion = "Powershell for Sharepoint 2010"
 New-SPEnterpriseSearchLanguageResourcePhrase -SearchApplication $srchSvcApp -Language $lang  -Type QuerySuggestionAlwaysSuggest -Name $newQuerySuggestion

Run the time Job:
$querySugestionTimer=Get-SPTimerJob|? {$_.Name -eq "Prepare Query Suggestions"}

$querySugestionTimer.RunNow()


Tuesday, February 28, 2012

Get and Renaming SPFolder c#

This is how you can rename a SPFolder. There is no need to use MoveTo() as suggested by others.
The user has to have rights to do it, or enclose the whole thing inside a

var siteId = "Guid of my site";
var webUrl= "Server relative path to my web";
SPSecurity.RunWithElevatedPrivileges(delegate(){
    using (SPSite elevatedSite = new SPSite(siteId))
   {
       using (SPWeb elevatedWeb = elevatedSite.OpenWeb(webUrl))
      {

          string requestFolderUrl = webUrl+ "/MYLIST/OldFolderName";
          SPFolder requestFolder = elevatedWeb.GetFolder(requestFolderUrl);

          if (requestFolder.Exists)
          {

               requestFolderItem[SPBuiltInFieldId.Title] = "NewName"; //not really needed for renaming
               //requestFolderItem[
SPBuiltInFieldId.BaseName] =  "NewName"; //this Fails.don't know why
               requestFolderItem["BaseName"] =  "NewName"; //this Works!
               //don't want to update the Modified time nor the modified by Info
              //If you want to modify this info use Update, and avoid being in a RunWithElevatedPrivileges
             ///because else you would have the System User registered
               requestFolderItem.SystemUpdate(false);

           }
      }
   }
}

Thursday, February 16, 2012

Remove Event Handlers from SPList Powershell

This is how you can  delete Event handlers from a SPList

$webUrl= "http://yoursite.com/subsite"
$listName = "myList"

$site = Get-SPSite($siteUrl)
$web = $site.OpenWeb()
$listWithEventHandlers = $web.Lists[$listName]

#you can find out the index of the eventhadler through a selector, or just beeing lazy
#and loop the eventhanlders


 $allEvenReceivers  = $list.EventReceivers
foreach($ev in $allEvenReceivers  )
{
   write-host $ev.Name;
}
$index = 0
$eventHandlerToDelete = $listWithEventHandlers.EventReceivers[$index]$eventHandlerToDelete.Delete()
$listWithEventHandlers.Update()

$web.Dispose()
$site.Dispose()

Access MasterPage catalog with Powershell

To acces the Masterpage catalog via Powershell, and then use it as a list the following script might help

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

clear
$siteUrl = "http://yourserver.com"

$masterPageCatalog = "_catalogs/masterPage"

$site = Get-SPSite $siteUrl

$rootWeb = $site.RootWeb;

$folder = $rootWeb.GetFolder($masterPageCatalog)

$masterPageCatList = $rootWeb.Lists[$folder.ParentListId]

#do some list operations on it


$rootWeb.Dispose()
$site.Dispose()

Wednesday, January 25, 2012

Reorder field in existing Contentype withPowershell

if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"}))
{
    Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear
$dirURL = "Url of the Content Type"
$contentTypeName = "ContentTypeName"
$fieldInternalName= "Internal name of the field to reorder"
$field0BasedIndex = 8 #Position on the contentytpe this field is wanted

if($site -ne $null){
    $web = $site.RootWeb
    if($web -ne $null){
        $ct = $web.ContentTypes[$contentTypeName]
        if($ct -ne $null){
            write-Host "content Type Found"  -foregroundcolor green
           
            $fields = New-Object 'System.Collections.Generic.List[string]' ;
            [Microsoft.SharePoint.SPFieldLinkCollection]$flinks = $ct.FieldLinks;
            #Read all the InternalNames of the FieldLinks into a list
            foreach($fieldLink in $flinks){
             $fields.Add($ct.Fields[$fieldLink.ID].InternalName);
            }
            if($fields.Contains($fieldInternalName)){           
                write-Host "Field found in Content Type" -foregroundcolor green;
                $indexFound = $fields.IndexOf($fieldInternalName)
                if($indexFound -ne $field0BasedIndex )
                {
                    $fields.RemoveAt($indexFound)
                    #insert or append the field
                    if($field0BasedIndex -le $fields.Count -1){
                        $fields.Insert( $field0BasedIndex,$fieldInternalName)
                    }
                    else{
                        $fields.Add($fieldInternalName);
                    }
                    #Add the array to the reorder
                    $flinks.Reorder($fields.ToArray());
                    #Update the ContentYpe
                    $ct.Update($true)
                 }
            }
            else{
               write-Host "Field not found in Content Type" -foregroundcolor red;
            }
        }
        else{
            write-Host "Content type not found"  -foregroundcolor red
        }
        $web.Update()
        $web.Dispose();
    }
    $site.Dispose();
}

Insert new Site Column in existing Contentype with PowerShell

# Check if Snap-in is loaded
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}

$dirURL = "Type here the abolute Url to the Sitecollection where the contentytpe is defined"
$contentTypeName = "Traktandum"
$fieldId = [Guid]"{516ae749-c8b4-4a9b-858f-50881aae4165}"  
#fieldId mus match the one on the fieldXML

$site = Get-SPSite -Identity $dirURL
if($site -ne $null){
    $web = $site.RootWeb
    if($web -ne $null){
        #Assign fieldXML variable with XML string for site column
        $fieldXML = '<Field
    Description="$Resources:MyCustom,Field_MyPortalOtherGuest_Description"
    DisplayName="$Resources:MyCustom,Field_MyPortalOtherGuest_DisplayName"
    Hidden="FALSE"
    Name="SomeName"
    Title="SomeName"
    Required="FALSE"
    Sealed ="FALSE"
    Sortable="FALSE"
    List="UserInfo"
    ShowField="ImnName"
    Mult="TRUE"
    Type="UserMulti"
    UserSelectionMode="0"
    UserSelectionScope="0"
    ID="{516ae749-c8b4-4a9b-858f-50881aae4165}"
    Group="$Resources:MyCustom,Field_Group"
    StaticName="SomeName" />'
    
        #Add the field to the web
        $web.Fields.AddFieldAsXml($fieldXML)
        $web.Update()

        $field = $web.AvailableFields[$fieldId]
        $ct = $web.ContentTypes[$contentTypeName]
        if($field -ne $null -and $ct -ne $null){
            #Delete any existing Field with that ID from the ContentType
            $ct.FieldLinks.Delete($fieldId)
            #Update the Contentype includeing childs
            $ct.Update($true, $true)
            #Creat a new SPFieldLink for that field and insert it to the ContentType
            $link = new-object Microsoft.SharePoint.SPFieldLink $field            
            $ct.FieldLinks.Add($link)
            $ct.Update($true, $true)
        }
        $web.Update()
        $web.Dispose()
    }
$site.Dispose()
}