Showing posts with label Powershell. Show all posts
Showing posts with label Powershell. Show all posts

Monday, April 2, 2012

Find SPLists without Default View

One issues why sometimes the search crawler in SharePoint takes too long, is because of the lack of Default View on the lists form the Site. See the C# Code and explanation at
http://blogs.technet.com/b/victorbutuza/archive/2010/01/15/crawl-taking-indefinitely-to-complete.aspx
This is the power-shell version of the c# code shown on the mentioned site.

 
if(-not(
Get-PSSnapin | Where { $_.Name -eq "Microsoft.SharePoint.PowerShell"})
) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
}
clear
$spwa = Get-SPWebApplication -Identity "http://myWebAppURL"
foreach ($osite in $spwa.Sites)
{
      foreach ($oweb in $osite.AllWebs)
      {
           write-host $oweb.Url
           write-host "========================================================="
           foreach ($olist in $oweb.Lists)
        {
            if ($olist.Hidden -eq $false)
            {
                  try
                {
                  write-host "Title: "  $olist.Title;
                    if ($olist.DefaultView -eq $null)
                    {
                                   write-host "ERROR: No default list view found " -ForegroundColor Red
                             }
                    else
                    { 
                        #remove this if you have lots of lists
                        write-host "DefaultViewURL: " $olist.DefaultViewUrl
                        write-host "DefaultViewTitle: " $olist.DefaultView.Title
                    }
                }
                catch
                {
                   write-host "ERROR"

                }
            }
            }
           write-host "========================================================="
        $oweb.Dispose();
      }
      $osite.Dispose();
}

Tuesday, March 27, 2012

Find out the attaches SPEventReceivers on a given SPList

Small script to find out what event receivers are attached to a given list / document library.
Of course, you don't need that if you can have the luxury of having SharePointManager on your server.

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

$url = "https://myservername/mysite/mysubweb"
$listWebRelativeUrl = "/lists/thelist" # for a doc lib just "/DocLibName"

$site = Get-SPSite $url
$web = $site.OpenWeb()
$list =$web.GetList($web.ServerRelativeUrl + $listWebRelativeUrl)
$list.EventReceivers | foreach{write-host $_.Type " " $_.Name " " $_.ID}


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

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()


Thursday, February 16, 2012

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

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()
}

Monday, April 11, 2011

Powershell Script to insert large amount of ListItems in Sharepoint List

A small script I wrote to insert a large amount of items in a custom list. It is just for testing purposes, so I can learn a little bit more about optimizing SPQueries and about ListView thresholds.

if((Get-PSSnapin -Name Microsoft.Sharepoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.Sharepoint.PowerShell
}
clear
#Get-Command  -Module Microsoft.Sharepoint.PowerShell
$assignment = Start-SPAssignment
$webUrl="http://myweburl/"
$listName = "OneMillionRecords"
$spWeb = Get-SPWeb -Identity $webUrl -AssignmentCollection $assignment
$template = $spWeb.ListTemplates["Custom List"] 
$listId=$spWeb.Lists.Add($listName,"List with one million records",$template)
$spNewList = $spWeb.Lists[$listName]
$spFieldTypeText = [Microsoft.SharePoint.SPFieldType]::Note
$spFieldTypeNumber = [Microsoft.SharePoint.SPFieldType]::Number
$spNewList.Fields.Add(“Description”,$spFieldTypeText,$false)
$spNewList.Fields.Add(“ItemNr”,$spFieldTypeNumber,$false)
$i =1
$max = 1000000
while ($i -le $max) {
$j=$i.ToString()
$title="Item $j"
$itemNr=$i
$description="The Item is called Item $j and is stored with some useless text"
$newItem=$spNewList.items.Add() 
$newItem["Title"] = $title
$newItem["ItemNr"] = $itemNr
$newItem["Description"]=$description
$newitem.Update()
Write-Host $title
$i=$i+1
}
#Dispose all objects
Stop-SPAssignment $assignment

Saturday, April 9, 2011

PowerShell: Create Users in active directory and Sharpoint 2010

Small powerschell script that creates an amount of users in the Active Directory and inserts them in the Sharepoint 2010

Import-Module ActiveDirectory
if((Get-PSSnapin -Name Microsoft.Sharepoint.PowerShell -ErrorAction SilentlyContinue) -eq $null)
{
 Add-PSSnapin Microsoft.Sharepoint.PowerShell
}
#Get-Command -Module ActiveDirectory
clear
$i =3
while ($i -le 100000) {
$j=$i.ToString()
$username="Dev$j"
$webUrl="http://sharepoint website url/"
$group="Development Owners"

New-ADUser -SamAccountName $username -Name $username -UserPrincipalName "$username@domain.com" -DisplayName "$username User" -GivenName $username -Surname "User" -AccountPassword (ConvertTo-SecureString -AsPlainText "pass@word1" -Force) -Enabled $true -PasswordNeverExpires $false -Path 'CN=Users,DC=Domain,DC=com'

New-SPUser -UserAlias "Domain\$username" -Web $webUrl -DisplayName "$username User" -Group $group

Set-SPUser -Identity "Domain\$username" -Web $webUrl  -SyncFromAD:$true
$i=$i+1
}