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

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:

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;

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:

Refresh GAC using Powershell

Scenario:
Refreshing GAC is always a painful thing.
Do IISReset / remove old stuff / put new one. Can we automate it ?

Solution:
Certainly.. mighty power-shell can do it easily

If you are running on new machine - you might need to relax executing policy

Set-ExecutionPolicy Unrestricted
Code:
iisreset /stop

Set-Alias Gacutil "C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin\gacutil.exe"

Gacutil /uf EntLibContrib.Data.OdpNet
Gacutil /i "MS ENT dlls\EntLibContrib.Data.OdpNet.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Caching
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Caching.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Common
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Common.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Data
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Data.dll"

Gacutil /uf Microsoft.Practices.EnterpriseLibrary.Logging
Gacutil /i "MS ENT dlls\Microsoft.Practices.EnterpriseLibrary.Logging.dll"

Gacutil /uf Microsoft.Practices.ServiceLocation
Gacutil /i "MS ENT dlls\Microsoft.Practices.ServiceLocation.dll"

Gacutil /uf Microsoft.Practices.Unity.Configuration
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Configuration.dll"

Gacutil /uf Microsoft.Practices.Unity
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.dll" 

Gacutil /uf Microsoft.Practices.Unity.Interception.Configuration
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Interception.Configuration.dll"

Gacutil /uf Microsoft.Practices.Unity.Interception
Gacutil /i "MS ENT dlls\Microsoft.Practices.Unity.Interception.dll" 

Gacutil /uf Telerik.Web.Design
Gacutil /i "Telerik.Web.Design.dll"

Gacutil /uf Telerik.Web.UI
Gacutil /i "Telerik\Telerik.Web.UI.dll" 

Gacutil /uf Telerik.Reporting
Gacutil /i "Telerik\Telerik.Reporting.dll"

Gacutil /uf Telerik.Web.UI.Skins
Gacutil /i "Telerik\Telerik.Web.UI.Skins.dll"

iisreset /start

Friday, December 14, 2012

Powershell to hide fields from edit form

Scenario:
We build a small solution for our client.
Solution had a custom UI for all CRUD operations and client want to block everyone from editing the list using Edit Form.

Solution:
While there can be many ways, considering site is running perfectly in PROD, writing a quick power shell will be enough.

Code:

cls
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

$webUrl = "http://sp2010/siteX"
$web = Get-SPWeb $webUrl
$list = $web.Lists.TryGetList("Tasks")

$fieldDisplayNames = "Status","Priority"
$showFields = $false 

$fieldDisplayNames |foreach {
 
$spfield = $list.Fields[$_]
$spfield.ShowInEditForm = $showFields
$spfield.Update()

}
Article:

Friday, September 21, 2012

SharePoint programatically apply claims

Scenario:
Claim based authentication is way to go if you want to have dynamic roles for user based on certain attribute of an item/document. But question is how to apply a claim to the item :)

Solution:
Sample code
Code:

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration.Claims;

namespace SKN
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            using (SPSite site = new SPSite("http://intranet/Sites/LoadTest"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.TryGetList("Shared Documents");
                    SPView view = list.Views["Missing Claims"];
                    SPQuery query = new SPQuery(view);
                   
                    foreach (SPListItem item in list.GetItems(query))
                    {
                        i = item.ID;
ApplyClaims(web, item, true, "0000" + item.ID.ToString(), true,"Myclient");
                    }
                }
            }

            Console.Write(i);
            Console.ReadKey();
        }

        /// 
        /// Applies claims to the item.
        /// 
public static void ApplyClaims(SPWeb web, SPListItem item,string claimValue , string client)
        {
            item.BreakRoleInheritance(false);

            SPClaimProviderManager claimMgr = SPClaimProviderManager.Local;
            if (claimMgr != null)
            {
               SPClaim claim = new                               SPClaim(Microsoft.IdentityModel.Claims.ClaimTypes.Role,
               claimValue,
Microsoft.IdentityModel.Claims.ClaimValueTypes.String,
SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, client));

                string userName = claimMgr.EncodeClaim(claim);

                // SPUser spUser = web.EnsureUser(userName);
                SPUserInfo info = new SPUserInfo
                {
                    LoginName = userName,
                    Name = claimValue 
                };

                SPRoleAssignment roleAssignmentClaim = new SPRoleAssignment(info.LoginName, info.Email, info.Name, info.Notes);
                roleAssignmentClaim.RoleDefinitionBindings.Add(web.RoleDefinitions["Read"]);
                item.RoleAssignments.Add(roleAssignmentClaim);
            }
        }

        /// 
        /// Adds the role assignment.
        /// 
        /// The item./// The role assignment.public static void AddRoleAssignment(SPListItem item, SPRoleAssignment roleAssignment)
        {
            bool isNotFound = true;
            foreach (SPRoleAssignment roleAssign in item.RoleAssignments)
            {
                if (roleAssign.Equals(roleAssignment))
                {
                    isNotFound = false;
                    break;
                }
            }

            if (isNotFound)
            {
                item.RoleAssignments.Add(roleAssignment);
            }

            item.SystemUpdate();
        }
    }
}

Friday, September 14, 2012

SharePoint Powershell Test Data script

Scenario:
Working on a project and we need to test the software limit of SharePoint 2010.
MS Documentation is not clear about things/ community blogs have different experience.
So without taking chance, here a small script to create test items

Solution:
Powershell script

Code:

cls
Remove-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue
Add-PSSnapin Microsoft.SharePoint.Powershell

$webUrl = Read-Host 'Please specify site url'
$web = Get-SPWeb $webUrl;
$list = $web.Lists.TryGetList("Announcements");
(1..50000)|%{
$item = $list.Items.Add();
$item["Title"]="Test";
$item.Update();
# Optional 
# $item.BreakRoleInheritance($True);
$item.ID
}
$web.Dispose()

Thursday, August 23, 2012

Powershell exporting user profile information

Scenario:
I was asked by my client to export User Profile data into Excel.

Solution:
Answer was Powershell. I googled and found a good script to start with, I just added few more things and tested it. Here's the script

Code:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

$siteUrl = "http://sp2010"
$outputFile = "C:\UserProfiles.csv"

$serviceContext = Get-SPServiceContext -Site $siteUrl
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($serviceContext);
$profiles = $profileManager.GetEnumerator()

Write-Host "Exporting profiles" 

$collection = @()
foreach ($profile in $profiles) {
 
  $profileData = "" | select "AccountName","FirstName", "LastName","PreferredName","WorkPhone"
   $profileData.AccountName = $profile["AccountName"].Value
   $profileData.FirstName = $profile["FirstName"].Value
   $profileData.LastName = $profile["LastName"].Value
   $profileData.PreferredName = $profile["PreferredName"].Value
   $profileData.WorkPhone = $profile["WorkPhone"].Value
   $collection += $profileData
}

$collection | Export-Csv $outputFile -NoTypeInformation
Article:
User Profile export

Thursday, March 1, 2012

SharePoint Powershell List Items

Scenario: SharePoint automation scripts related to list items.
Code:

#Load SharePoint Snap In
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
function xApproveAll-SPItems
{  
 param ($Url, $ListName) 

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

$folders = $list.Folders
foreach ($folder in $folders)
{
     $folder["_ModerationStatus"] = 0
     $folder.Update()
}  

$items = $list.Items
foreach ($item in $items)
{
     Write-Host "Approving : " + $intIndex 
     $item["_ModerationStatus"] = 0
     $item.Update()
}  

 $web.Dispose()
 Write-Host "Approved all the documents successfully" -foregroundcolor Green  
}

function xDeleteAll-SPItems
{  
 param ($Url, $ListName) 

$web = Get-SPWeb $Url
$list = $web.Lists.TryGetList($ListName)
$itemCount = $list.ItemCount
for($intIndex = $itemCount; $intIndex -gt 0; $intIndex--) 
{ 
        Write-Host "Deleting : " + $intIndex 
        $list.Items[$intIndex-1].Delete();
}

 $web.Dispose()

}
$url=Read-Host "Enter site url"
$listName=Read-Host "Enter list library name"

xApproveAll-SPItems $url $listName
xDeleteAll-SPItems $url $listName

Tuesday, February 28, 2012

Powershell and SharePoint Permissions

Scenario: SharePoint provide options to have security at different level, here some related functions which you can use.
Code:

#Load SharePoint Snap In
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
function Create-SPGroupInWeb
{
 param ($Url, $GroupName, $PermissionLevel, $Description)
 $web = Get-SPWeb -Identity $Url
 if ($web.SiteGroups[$GroupName] -ne $null)
 {
  Write-Host "Group $GroupName already exists!" -foregroundcolor Red
 }
 else
 {
  $web.SiteGroups.Add($GroupName, $web.Site.Owner, $web.Site.Owner, $Description)
  $group = $web.SiteGroups[$GroupName]
  $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
  $roleDefinition = $web.Site.RootWeb.RoleDefinitions[$PermissionLevel]
  $roleAssignment.RoleDefinitionBindings.Add($roleDefinition)
  $web.RoleAssignments.Add($roleAssignment)
  $web.Update()
  Write-Host "Group $GroupName created successfully" -foregroundcolor Green
 }

 $web.Dispose()
}
function Remove-SPPermisssionFromListGroup
{
 param ($Url, $ListName, $GroupName, $PermissionLevel)
 $web = Get-SPWeb -Identity $Url
 $list = $web.Lists.TryGetList($ListName)
 if ($list -ne $null)
 {
  if ($list.HasUniqueRoleAssignments -eq $False)
  {
   $list.BreakRoleInheritance($True)
  }
  else
  {
   if ($web.SiteGroups[$GroupName] -ne $null)
   {
    $group = $web.SiteGroups[$GroupName]
    $roleAssign = $list.RoleAssignments.GetAssignmentByPrincipal($group);
    $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
    $roleAssign.RoleDefinitionBindings.Remove($roleDefinition);
    $roleAssign.Update();
    $list.Update();
    Write-Host "Successfully removed $PermissionLevel permission from $GroupName group in $ListName list." -foregroundcolor Green
   }
   else
   {
    Write-Host "Group $GroupName does not exist." -foregroundcolor Red
   }
  }
 }
 else
 {
  Write-Host "List $ListName does not exist!" -foregroundcolor Red
 }

 $web.Dispose()
}
function Add-SPPermissionToListGroup
{
 param ($Url, $ListName, $GroupName, $PermissionLevel)
 $web = Get-SPWeb -Identity $Url
 $list = $web.Lists.TryGetList($ListName)
 if ($list -ne $null)
 {
  if ($list.HasUniqueRoleAssignments -eq $False)
  {
   $list.BreakRoleInheritance($True)
  }
  else
  {
   if ($web.SiteGroups[$GroupName] -ne $null)
   {
    $group = $web.SiteGroups[$GroupName]
    $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
    $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
    $roleAssignment.RoleDefinitionBindings.Add($roleDefinition);
    $list.RoleAssignments.Add($roleAssignment)
    $list.Update();
    Write-Host "Successfully added $PermissionLevel permission to $GroupName group in $ListName list. " -foregroundcolor Green
   }
   else
   {
    Write-Host "Group $GroupName does not exist." -foregroundcolor Red
   }
  }
 }

 $web.Dispose()
}
function Remove-SPPermisssionFromListItemGroupSpecific
{
 param ($Url, $ListName, $GroupName, $PermissionLevel)
 $web = Get-SPWeb -Identity $Url
 $list = $web.Lists.TryGetList($ListName)
 if ($list -ne $null)
 {
  foreach ($item in $list.Items) 
  {
   if ($item.HasUniqueRoleAssignments -eq $False)
   {
    $item.BreakRoleInheritance($True)
   }
   else
   {
    if ($web.SiteGroups[$GroupName] -ne $null)
    {
     $group = $web.SiteGroups[$GroupName]
     $roleAssign = $item.RoleAssignments.GetAssignmentByPrincipal($group);
     $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
     $roleAssign.RoleDefinitionBindings.Remove($roleDefinition);
     $roleAssign.Update();
     $item.SystemUpdate();                    
     Write-Host "Successfully removed $PermissionLevel permission from $GroupName group in $ListName list." -foregroundcolor Green
    }
    else
    {
     Write-Host "Group $GroupName does not exist." -foregroundcolor Red
    }
   }
  }
 }
 else
 {
  Write-Host "List $ListName does not exist!" -foregroundcolor Red
 }

 $web.Dispose()
}
function Remove-SPPermisssionFromListItemGroupAll
{
 param ($Url, $ListName, $GroupName)
 $web = Get-SPWeb -Identity $Url
 $list = $web.Lists.TryGetList($ListName)
 if ($list -ne $null)
 {
  foreach ($item in $list.Items) 
  {
   if ($item.HasUniqueRoleAssignments -eq $False)
   {
    $item.BreakRoleInheritance($True)
   }
   else
   {
    if ($web.SiteGroups[$GroupName] -ne $null)
    {
     $group = $web.SiteGroups[$GroupName]
                    $item.RoleAssignments.Remove($group)
     $item.SystemUpdate();                    
     Write-Host "Successfully removed $PermissionLevel permission from $GroupName group in $ListName list." -foregroundcolor Green
    }
    else
    {
     Write-Host "Group $GroupName does not exist." -foregroundcolor Red
    }
   }
  }
 }
 else
 {
  Write-Host "List $ListName does not exist!" -foregroundcolor Red
 }

 $web.Dispose()
}
function Add-SPPermissionToListItemGroup
{
 param ($Url, $ListName, $GroupName, $PermissionLevel)
 $web = Get-SPWeb -Identity $Url
 $list = $web.Lists.TryGetList($ListName)
 if ($list -ne $null)
 {
  foreach ($item in $list.Items) 
  {
   if ($item.HasUniqueRoleAssignments -eq $False)
   {
    $item.BreakRoleInheritance($True)
   }
   else
   {
    if ($web.SiteGroups[$GroupName] -ne $null)
    {
     $group = $web.SiteGroups[$GroupName]
     $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
     $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
     $roleAssignment.RoleDefinitionBindings.Add($roleDefinition);
     $item.RoleAssignments.Add($roleAssignment)
     $item.SystemUpdate();
     Write-Host "Successfully added $PermissionLevel permission to $GroupName group in $ListName list. " -foregroundcolor Green
    }
    else
    {
     Write-Host "Group $GroupName does not exist." -foregroundcolor Red
    }
   }
  }
 }

 $web.Dispose()
}
function Add-SPPermissionToListItemGroupConditional
{
 param ($Url, $ListName, $Caml, $GroupName, $PermissionLevel)
 $web = Get-SPWeb -Identity $Url
 $list = $web.Lists.TryGetList($ListName)
 if ($list -ne $null)
 {
        $spQuery = New-Object Microsoft.SharePoint.SPQuery        
        $spQuery.Query = $Caml
        $spQuery.RowLimit = 10000
        $listItems = $list.GetItems($spQuery)        
        $listItems.Count
  foreach ($item in $listItems) 
  {
   if ($item.HasUniqueRoleAssignments -eq $False)
   {
    $item.BreakRoleInheritance($True)
   }
   else
   {
    if ($web.SiteGroups[$GroupName] -ne $null)
    {
     $group = $web.SiteGroups[$GroupName]
     $roleAssignment = new-object Microsoft.SharePoint.SPRoleAssignment($group)
     $roleDefinition = $web.RoleDefinitions[$PermissionLevel];
     $roleAssignment.RoleDefinitionBindings.Add($roleDefinition);
     $item.RoleAssignments.Add($roleAssignment)
     $item.SystemUpdate();
     Write-Host "Successfully added $PermissionLevel permission to $GroupName group in $ListName list. " -foregroundcolor Green
    }
    else
    {
     Write-Host "Group $GroupName does not exist." -foregroundcolor Red
    }
   }
  }
 }

 $web.Dispose()
}
$Url=Read-Host "Enter site url"

Remove-SPPermisssionFromListItemGroupSpecific $Url "Shared Documents" "Team Visitors" "Read"
Remove-SPPermisssionFromListItemGroupAll $Url "Shared Documents" "Team Visitors"
Add-SPPermissionToListItemGroup $Url "Shared Documents" "Team Visitors" "Contribute"
Add-SPPermissionToListItemGroupConditional $Url "Shared Documents" "<Where><Eq><FieldRef Name='Create' /><Value Type='Boolean'>1</Value></Eq></Where>" "Team Visitors" "Contribute"

Monday, December 12, 2011

Powershell and search metadata properties

Scenario:
While working with one of client we created a quick script for creating / recreating metadata properties for search. Thought of sharing :)

This script will drop exiting property with same name [ if exist ] and create it again. Also I have provided samples of different field types.

Code:


#####################################################################
# Main Function
#####################################################################

function PromptUser {param($message)

write-host -f Red $message

write-host -f Red "Press enter to continue ... and N to exit"

$keyentered = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

If ($keyentered.VirtualKeyCode -eq 78)
{
exit
}
}

function DropMetadataProperties {param ($ServiceApplicationName, $MetadataPropertyName)

$category = Get-SPEnterpriseSearchMetadataCategory –Identity "Business Data" -SearchApplication $searchapp

If (Get-SPEnterpriseSearchMetadataManagedProperty -SearchApplication $searchapp -Identity $MetadataPropertyName -ea "silentlycontinue")
{
write-host -f Green "MetaProperty already exists, we delete it so it can be reacreated."
$prop = Get-SPEnterpriseSearchMetadataManagedProperty -SearchApplication $searchapp -Identity $MetadataPropertyName
$prop.DeleteAllMappings()
$prop.Delete()
$searchapp.Update()
}

if (!$?)
{
PromptUser("An error has occurred")
}
}

function CreateMetadataProperties {param ( $ServiceApplicationName, $MetadataPropertyName, $CrawledProperty, $VariantType, $Type, $HasMultipleValues, $IsSortable)

$category = Get-SPEnterpriseSearchMetadataCategory –Identity "Business Data" -SearchApplication $searchapp

$crawledproperty = Get-SPEnterpriseSearchMetadataCrawledProperty -SearchApplication $searchapp -Category $category -VariantType $VariantType -Name $CrawledProperty
If (!($crawledproperty -eq $null))
{
$managedproperty = New-SPEnterpriseSearchMetadataManagedProperty -SearchApplication $searchapp -Name $MetadataPropertyName -Type $Type

If ($IsSortable -eq $True)
{
$managedproperty.MaxCharactersInPropertyStoreIndex = 64
$managedproperty.Update()
}

If ($HasMultipleValues -eq $True)
{
$managedproperty.HasMultipleValues = $true
$managedproperty.Update()
}


New-SPEnterpriseSearchMetadataMapping -SearchApplication $searchapp -ManagedProperty $managedproperty -CrawledProperty $crawledproperty
}
else
{
write-host -f Red "Crawl property is missing, you might need to recrawl your content source to get it."
}

if (!$?)
{
PromptUser("An error has occurred")
}
}

###################################################################################
# Drop metadata properties
###################################################################################

$searchapp = Get-SPEnterpriseSearchServiceApplication
if (!$?)
{
PromptUser("Could not find a valid Search Service Application.")
EXIT
}

$searchAppName = $searchapp.Name


# Client Metadata properties
DropMetadataProperties $searchAppName "xxClientName"

###################################################################################
# Create metadata properties
###################################################################################

# VariantType = (31 for string , 20 for integer , 11 for boolean , 64 for datetime )
# Type = (1 for string , 2 for integer , 5 for Yes/No , 4 for datetime )

### Text Field
DropMetadataProperties $searchAppName "xxClientName"
CreateMetadataProperties $searchAppName "xxClientName" "Client.ClientName" 31 1 $False $True

### Integer Field
DropMetadataProperties $searchAppName "xxClientID"
CreateMetadataProperties $searchAppName "xxClientID" "Clients.ClientID" 20 2 $False $False

### YES/No Field
DropMetadataProperties $searchAppName "xxIsActive"
CreateMetadataProperties $searchAppName "xxIsActive" "Clients.IsActive" 11 5 $False $False

### Date Field
DropMetadataProperties $searchAppName "xxEndDate"
CreateMetadataProperties $searchAppName "xxEndDate" "Clients.EndDate" 64 4 $False $False
Please do leave comments on if it worked for you or any suggestion to improve it.

Monday, October 31, 2011

Error in Activate Features from Visual Studio

Scenario:
I was re-deploying a solution from Visual Studio. My solution had custom Fields / Content Type declarations and was getting deployed to an existing site collection.

I noticed following errors :

Error occurred in deployment step 'Activate Features': The field with Id {GUID} defined in feature {GUID} was found in the current site collection or in a subsite.

OR

Error occurred in deployment step 'Activate Features': The content type with Id {GUID} defined in feature {GUID} was found in the current site collection or in a subsite.

Reason:
First of all this is not a problem with Solution. As if you use STSADM / Powershell to deploy and activate features, it will work fine.

Actually there is something going on with VSSPHost4 process.

Solution:
There are 2 solutions to this issue.

1. Close the Visual Studio and start again :)

2. Kill VSSPHost4 process. This can be done from SharePoint Powershell Management shell command prompt

stop-process -processname vssphost4 -force

Monday, April 25, 2011

SP2010 : Backup Restore with Powershell

Scenario:
I have to do this often for my client. While working on SPD , things can get screwed and so I need a quick backup's at different stages.

Also In case I am screwed I want to recover from my latest backup quickly.

Solution:
Powershell, yes :)

How it works:
1. Create a folder where you want to maintain your backups
2. Copy the backup.ps1 and restore.ps1 in same folder.
3. Make sure you have the right site collection url , its hard-coded but can be parameterized but then it will not be fast ;)
4. Keep the PS Command open and run backup / restore scripts as you want.

Backup.ps1:

$siteCollUrl = "http://intranet.contoso.com/"

$a = Get-Date
$currentfolder = (Get-Location -PSProvider FileSystem).ProviderPath

$filename = $currentFolder + "\backup_" + $a.Day.ToString() + "." + $a.Month.ToString() + "." + $a.Year.ToString() + "." + $a.Hour.ToString() + "." + $a.Minute.ToString() + "." + $a.Second.ToString() + ".bak"

Backup-SPSite $siteCollUrl -Path $filename
Restore.ps1:
$siteCollUrl = "http://intranet.contoso.com/"

$currentfolder = (Get-Location -PSProvider FileSystem).ProviderPath
$collFiles = @(gci $currentfolder | Where-Object {$_.name -like "backup_*"})

if($collFiles.Count -gt 0 )
{
$objFile = $collFiles | Select-Object -Last 1;
$filename = $objFile.FullName
Restore-SPSite $siteCollUrl -Path $filename -force
}
else
{
Write-Host "No backup to restore"
}

Tuesday, April 19, 2011

SP2010 : Powershell deployment

Scenario:
We need this all the time to retract / remove / add / deploy solution.Want to know what I use ?

Solution:
Powershell

Script:

####################################################################################################
# Function
####################################################################################################

function RetractAndRemoveSolution {param ($SolutionPackageName, $DeployedGlobally)
$solution = Get-SPSolution | where-object {$_.Name -eq $SolutionPackageName}

# check to see if solution package has been installed
if ($solution -ne $null)
{
if($solution.Deployed -eq $true)
{
if( $DeployedGlobally -eq $true)
{
Uninstall-SPSolution -Identity $SolutionPackageName -Local -Confirm:$False
}
else
{
Uninstall-SPSolution -Identity $SolutionPackageName -AllWebApplications -Local -Confirm:$False
}
}

Remove-SPSolution -Identity $SolutionPackageName -Confirm:$false
}
}

###########################################################################################
# To uninstall/remove custom solutions in central administration.
###########################################################################################

Write-Host "Removing solutions"

RetractAndRemoveSolution "CustomSolution.wsp" $false
RetractAndRemoveSolution "CustomSolutionGlobal.wsp" $true

###########################################################################################
# To add/deploy custom solutions in central administration.
###########################################################################################

Write-Host "Adding Solutions"

$currentfolder = (Get-Location -PSProvider FileSystem).ProviderPath
Add-SPSolution -LiteralPath $currentfolder"\CustomSolution.wsp"

###########################################################################################
# To deploy custom solutions to newly created site collection
# ( Mainly for use in DEV only, recommended to deploy using Central Admin UI for other environments )
###########################################################################################

Write-Host "Installing Solutions"

$webInsite = "http://intranet.contoso.com"
Install-SPSolution -Identity "CustomSolution" –WebApplication $webInsite –GACDeployment

###########################################################################################
# Reset IIS / Restart Services / Exit to ensure not binary is locked with Powershell Editor
###########################################################################################

iisreset

net stop "Sharepoint Server Search 14"
net start "Sharepoint Server Search 14"

exit

Friday, July 9, 2010

Setting server using Powershell

Scenario:
Already I am a big fan of Powershell. I thought of setting my solution using Power shell on a new machine.Script just worked great.

Let me share few of the them which we all use often.

Code:
###########################################################################################
# Create a new WebApplication
###########################################################################################

$newWebApplicationUrl = "http://intranet.contoso.com"
$ApplicationPoolAccount = Get-SPManagedAccount "contoso\Administrator"
New-SPWebApplication -Name "CustomApplication" -ApplicationPool "CustomApplication-80" -ApplicationPoolAccount $ApplicationPoolAccount -Port 80 –Url $newWebApplicationUrl
###########################################################################################
#Enabled Claim Based authentication for Existing Web Application:
###########################################################################################
$webApplicationUrl = "http://intranet.contoso.com"
$webapp= Get-SPWebApplication $webApplicationUrl
$webapp.UseClaimsAuthentication
$webapp.UseClaimsAuthentication=$True
$webapp.Update()
$webapp.ProvisionGlobally()
iisreset
###########################################################################################
# Add new managed path for Projects Site Collections:
###########################################################################################
$webApplicationUrl = "http://intranet.contoso.com"
New-SPManagedPath –RelativeURL "/ProjectCentral" -WebApplication $webApplicationUrl -Explicit
New-SPManagedPath –RelativeURL "/Projects" -WebApplication $webApplicationUrl
###########################################################################################
# To add/deploy custom solutions in central administration.
###########################################################################################
Add-SPSolution -LiteralPath CustomApplication.wsp 
Install-SPSolution -Identity CustomApplication.wsp –AllWebApplications –GACDeployment
###########################################################################################
# To create a site collection:
###########################################################################################
$projectCentralUrl = "http://intranet.contoso.com"
$siteTitle="Project Central";
$owner="contoso\administrator"
$template=”STS#0”
$newSiteColl = New-SPSite $projectCentralUrl –Name $siteTitle –OwnerAlias $owner –Template $template
$newSiteColl.Dispose()
###########################################################################################
# Enable publishing infrastructure features
###########################################################################################
Enable-SPFeature -Identity PublishingSite -url $projectCentralUrl 
Enable-SPFeature -Identity PublishingWeb -url $projectCentralUrl
###########################################################################################
# Enable Performance Point feature at Site Collection level
###########################################################################################
Enable-SPFeature -Identity PPSSiteCollectionMaster -url $projectCentralUrl
###############################################################################################
# To create a subsite for TeamManagement under Project Central with unique permissions:
###############################################################################################
$webTeamManagement = New-SPWeb –Name "Team Management" –Url "$projectCentralUrl/TeamManagement" -Template "STS#1" –UniquePermissions

#Owners group creation ( Assuming Client Authentication Enabled )

$owner = $webTeamManagement.AllUsers["i:0#.w|contoso\administrator"]
$ownerGroupName ="$webTeamManagement Owners"
$webTeamManagement.SiteGroups.Add($ownerGroupName,$owner,$owner,$ownerGroupName)
$ownerGrp = $webTeamManagement.SiteGroups[$ownerGroupName]
$webTeamManagement.AssociatedOwnerGroup = $ownerGrp
$ownerRole="Full Control"
$ownerAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($ownerGrp)
$ownerRoleDefinition=$webTeamManagement.RoleDefinitions[$ownerRole]
$ownerAssignment.RoleDefinitionBindings.Add($ownerRoleDefinition)
$webTeamManagement.RoleAssignments.Add($ownerAssignment);

#Members group creation ( Assuming Client Authentication Enabled )

$member = $webTeamManagement.AllUsers["i:0#.w|contoso\administrator"]
$memberGroupName ="$webTeamManagement Members"
$webTeamManagement.SiteGroups.Add($memberGroupName,$member,$member,$memberGroupName)
$memberGrp = $webTeamManagement.SiteGroups[$memberGroupName]
$webTeamManagement.AssociatedMemberGroup = $memberGrp
$memberRole="Contribute"
$memberAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($memberGrp)
$memberRoleDefinition=$webTeamManagement.RoleDefinitions[$memberRole]
$memberAssignment.RoleDefinitionBindings.Add($memberRoleDefinition)
$webTeamManagement.RoleAssignments.Add($memberAssignment);

#Visitors group creation ( Assuming Client Authentication Enabled )

$visitor = $webTeamManagement.AllUsers["i:0#.w|contoso\administrator"]
$visitorGroupName ="$webTeamManagement Visitors"
$webTeamManagement.SiteGroups.Add($visitorGroupName,$visitor,$visitor,$visitorGroupName)
$visitorGrp = $webTeamManagement.SiteGroups[$visitorGroupName]
$webTeamManagement.AssociatedVisitorGroup = $visitorGrp
$visitorRole="Read"
$visitorAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($visitorGrp)
$visitorRoleDefinition=$webTeamManagement.RoleDefinitions[$visitorRole]
$visitorAssignment.RoleDefinitionBindings.Add($visitorRoleDefinition)
$webTeamManagement.RoleAssignments.Add($visitorAssignment);

$webTeamManagement.Update()
$webTeamManagement.Dispose()
####################################################################################################
# To create a subsite for Report Center under Project Management with unique permissions:
####################################################################################################
$webReportCenter = New-SPWeb –Name "Report Center" –Url "$projectCentralUrl/BI" -Template "BICENTERSITE#0" –UniquePermissions

#Owners group creation

$owner = $webReportCenter.AllUsers["i:0#.w|contoso\administrator"]
$ownerGroupName ="$webReportCenter Owners"
$webReportCenter.SiteGroups.Add($ownerGroupName,$owner,$owner,$ownerGroupName)
$ownerGrp = $webReportCenter.SiteGroups[$ownerGroupName]
$webReportCenter.AssociatedOwnerGroup = $ownerGrp
$ownerRole="Full Control"
$ownerAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($ownerGrp)
$ownerRoleDefinition=$webReportCenter.RoleDefinitions[$ownerRole]
$ownerAssignment.RoleDefinitionBindings.Add($ownerRoleDefinition)
$webReportCenter.RoleAssignments.Add($ownerAssignment);

#Members group creation

$member = $webReportCenter.AllUsers["i:0#.w|contoso\administrator"]
$memberGroupName ="$webReportCenter Members"
$webReportCenter.SiteGroups.Add($memberGroupName,$member,$member,$memberGroupName)
$memberGrp = $webReportCenter.SiteGroups[$memberGroupName]
$webReportCenter.AssociatedMemberGroup = $memberGrp
$memberRole="Contribute"
$memberAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($memberGrp)
$memberRoleDefinition=$webReportCenter.RoleDefinitions[$memberRole]
$memberAssignment.RoleDefinitionBindings.Add($memberRoleDefinition)
$webReportCenter.RoleAssignments.Add($memberAssignment);

#Visitors group creation

$visitor = $webReportCenter.AllUsers["i:0#.w|contoso\administrator"]
$visitorGroupName ="$webReportCenter Visitors"
$webReportCenter.SiteGroups.Add($visitorGroupName,$visitor,$visitor,$visitorGroupName)
$visitorGrp = $webReportCenter.SiteGroups[$visitorGroupName]
$webReportCenter.AssociatedVisitorGroup = $visitorGrp
$visitorRole="Read"
$visitorAssignment = New-Object Microsoft.SharePoint.SPRoleAssignment($visitorGrp)
$visitorRoleDefinition=$webReportCenter.RoleDefinitions[$visitorRole]
$visitorAssignment.RoleDefinitionBindings.Add($visitorRoleDefinition)
$webReportCenter.RoleAssignments.Add($visitorAssignment);

$webReportCenter.Update()
$webReportCenter.Dispose()
####################################################################################################
# To create FAST Search Center needs to activate Sharepoint Server Public Infrastructure feature:
####################################################################################################
$webSearch = New-SPWeb –Name "Search" -Url "$projectCentralUrl/Search" -Template "SRCHCENTERFAST#0"
$webSearch.Dispose()
####################################################################################################
# Activate Site Collection Features & Site Features of My Workspace:
####################################################################################################
Enable-SPFeature -Identity "CustomSolution_XSLTFiles" –Url $projectCentralUrl
Enable-SPFeature -Identity "CustomSolution_SavedSearchesListInstance" –Url $projectCentralUrl
Enable-SPFeature -Identity "CustomApplication_TeamManagementSiteFeature" –Url $projectCentralUrl
Enable-SPFeature -Identity "ProjectXSNForms" –Url $projectCentralUrl
####################################################################################################
# Activate Features on Project Management:
####################################################################################################
Enable-SPFeature -Identity "CustomSolution_FeatureX" –Url "$projectCentralUrl/TeamManagement"
####################################################################################################
# Get new web objects for all the webs
####################################################################################################
$projectCentralUrl = "http://intranet.contoso.com"

$webProjectCentral = Get-SPWeb "$projectCentralUrl"
$webTeamManagement = Get-SPWeb "$projectCentralUrl/TeamManagement"
$webReportCenter = Get-SPWeb "$projectCentralUrl/bi"
$webSearch = Get-SPWeb "$projectCentralUrl/search"
####################################################################################################
# Adjusting the master page from OOTB to CustomApplication based master pages
####################################################################################################
$webTeamManagement.Navigation.UseShared = $true

$pubWebProjectCentral = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($webprojectCentral)
$pubWebProjectCentral.IncludeSubsitesinNavigation=$True
$pubWebProjectCentral.CustomMasterUrl.SetValue($pubWebProjectCentral .CustomMasterUrl.Value.Replace("v4","Custom"))
$pubWebProjectCentral.MasterUrl.SetValue($pubWebProjectCentral .MasterUrl.Value.Replace("v4","Custom"))

$pubWebSearch = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($webSearch)
$pubWebSearch.CustomMasterUrl.SetValue($pubWebSearch.CustomMasterUrl.Value.Replace("minimal","CustomApplication_minimal"))
############################################################################################
# Adjusting the search center url
###########################################################################################
$searchUrl="/Search/Pages"
$webProjectCentral.AllProperties["SRCH_ENH_FTR_URL"] = $searchUrl
$webProjectCentral.AllProperties["SRCH_SITE_DROPDOWN_MODE"] = "ShowDD"
############################################################################################
# Update Web objects and dispose them
###########################################################################################

$pubWebProjectCentral.Update()
$pubWebSearch.Update()
$webProjectCentral Update()
$webTeamManagement.Update()
$webReportCenter.Update()
$webSearch.Update()

$webSearch.Dispose()
$webReportCenter.Dispose()
$webTeamManagement.Dispose()
$webProjectCentral.Dispose()
####################################################################################################
# To associate workflow to list
####################################################################################################
$projectCentralUrl = "http://intranet.contoso.com"

$web = Get-SPWeb "$projectCentralUrl/TeamManagement"
$list = $web.Lists.TryGetList("Project Forms")

$workflowInstanceName = "Project Site Status"
$workflowName = "CustomApplication-New Project Site Collection WF"

$historylistguid =$web.Lists.Add("Project Workflow History","",140)
$historylist =$web.Lists[$historylistguid]

$tasklistguid =$web.Lists.Add("Project Workflow Tasks","",107)
$tasklist=$web.Lists[$tasklistguid]

$culture=new-object System.Globalization.CultureInfo("en-US")
$basetemplate = $web.WorkflowTemplates.GetTemplateByName($workflowName,$culture)
$workflowAssociation=[Microsoft.SharePoint.Workflow.SPWorkflowAssociation]::CreateListAssociation($basetemplate,$workflowInstanceName ,$taskList,$historyList)
$workflowAssociation.AutoStartCreate = $True;

$list.WorkflowAssociations.Add($workflowAssociation)
$list.Update();
$web.Dispose()
####################################################################################################
# Create a new site collection
####################################################################################################
$ProjectSeriesID = "00001"
$newSiteCollectionUrl = "http://intranet.contoso.com/Projects/$ProjectSeriesID"
$owner="contoso\administrator"
$template=Get-SPWebTemplate "CustomApplicationSiteDefinition#0"
$siteTitle=$ProjectSeriesID
$newProjectSiteCollection = New-SPSite -URL $newSiteCollectionUrl -Name $siteTitle -OwnerAlias $owner -Template $template
$newProjectSiteCollection.Dispose()
####################################################################################################
# Adding a new link to Link List
####################################################################################################
$siteCollectionUrlForSitePool = "http://intranet.contoso.com"
$sitecoll=Get-SPSite $siteCollectionUrlForSitePool;
$webTeamManagement= Get-SPWeb "http://intranet.contoso.com/TeamManagement"
$List=$webTeamManagement.Lists["My Links"];
$item=$List.Items.Add()
$item["Title"]="Project Site"
$item["Site Url"]="http://intranet.contoso.com/Projects/00001"
$item.update()
$List.update()
$webTeamManagement.Dispose()
####################################################################################################
# This will switch the home page for TeamManagement with a tabbed UI
####################################################################################################
$projectCentralUrl = "http://intranet.contoso.com"
$webProjectCentral = Get-SPWeb "$projectCentralUrl/TeamManagement"
$sfile = $webProjectCentral.GetFile("default.aspx")
$dfile = $webProjectCentral.GetFile("home.aspx")
$dfile.CheckOut()
$dfile.SaveBinary($sfile.OpenBinary())
$dfile.CheckIn("done using code")
$webProjectCentral.Update()
####################################################################################################
#Remove Team Management Sub Site
####################################################################################################
$projectCentralUrl = "http://intranet.contoso.com"
Remove-SPWeb "$projectCentralUrl/CaseManagement"
####################################################################################################
# Remove Site Collection
####################################################################################################
$projectCentralUrl = "http://intranet.contoso.com"
Remove-SPSite -Identity $projectCentralUrl -GradualDelete -Confirm:$False
####################################################################################################
#Remove WebApplication with content databases and IIS
####################################################################################################
$projectCentralUrl = "http://intranet.contoso.com"
Remove-SPWebApplication $projectCentralUrl -Confirm -DeleteIISSite -RemoveContentDatabases
####################################################################################################
# Retracting and Removing CustomApplication Solution
###################################################################################################
$solutionPackageName = "CustomApplication.wsp"
$solution = Get-SPSolution | where-object {$_.Name -eq $solutionPackageName}

# check to see if solution package has been installed

if ($solution -ne $null) {
if($solution.Deployed -eq $true)
{
Uninstall-SPSolution -Identity $solutionPackageName -AllWebApplications -Local -Confirm:$False
}
}

Remove-SPSolution -Identity $solutionPackageName -Confirm:$false
Article:
Search center options , Some more commands

Thursday, June 24, 2010

Enable Claim Based Authentication for existing webapplication

Scenario:
While playing around with Claim provider I wanted to change my existing web application to use Claim provider , no UI option in Central Administration

Solution:
In SP2007 when ever Central Admin is missing an operation good chance was that STSADM will have something,so thinking of same. I knocked the door of POWERSHELL

Code:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

$webApplicationUrl=Read-Host "Enter a web application url"
$webapp= Get-SPWebApplication $webApplicationUrl 
$webapp.UseClaimsAuthentication
$webapp.UseClaimsAuthentication=$True
$webapp.Update()
$webapp.ProvisionGlobally()
iisreset

Monday, March 29, 2010

Powershell warning prompts

Scenario:
I downloaded some powershell commandlets from web and while trying to execute them. I got the following warning

Security Warning
Run only scripts that you trust. While scripts from the Internet can be useful, this script can potentially harm your
computer. Do you want to run C:\moss-script-collection\Get-XYZ.ps1?
[D] Do not run [R] Run once [S] Suspend [?] Help (default is "D"):


Solution:
This is because of in-build security of Powershell to block files downloaded from untrusted locations including World Wide Web.

If you really trust the source and script and want to run the script , you can choose from one of the optioned mentioned but If you need to run this script often and you dont want this propmpt to bug you again and again then ---

Steps:
1. Create a new file with ps1 extension i.e. newFile.ps1
2. Open the file you downloaded from WWW and copy all the content
3. Paste it now to newFile.ps1 file
4. Use the newFile.ps1 going forward it will work without prompting

As you see this was just a workaround, there are other ways also to make the original file work rather than creating a new one. But I found this one easier :)

SharePoint 2010 and Powershell

Scenario:
Powershell is making its way in all the Microsoft Server products and also is a great scripting language for SP2010. In SP2007 we had STSADM ( which is still not dead fully ). I was just playing around (again) on a small script I want to test.

Solution:
Please login to SharePoint 2010 box and Start Powershell. This will load the SharePoint snap-in automatically. Which mean Powershell is now ready and under stand SharePoint APIs.

I have used some commandlets from the following Powershell Blog( awesome )

Powershell Snippets :

# Declaring a variable 
$sitecollectionurl = "http://sp2010/sites/client3"

# Concating string
$weburl = "$sitecollectionurl/subsite"

# Logging current date
"$(Get-Date -f o) Start Logging"

# Changing the current directory
cd 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN\'

# Calling the STSADM commands
.\STSADM.EXE -o createsite -url "http://sp2010/sites/client1" -sitetemplate STS#1 -owneremail "admin@email.com" -ownerlogin sp2010\administrator -title "client1"

# Calling the STSADM commands using variable
.\STSADM.EXE -o createsite -url "$sitecollectionurl" -sitetemplate STS#1 -owneremail "admin@email.com" -ownerlogin sp2010\administrator -title "client1"

# Calling a Powershell CommandLets
.\Add-SPList -url "http://sp2010/sites/client1" -Name "ClientDocuments" -Description "Client Docs" -Type "Document Library"

# Calling a Powershell CommandLets using variable
.\Add-SPList -url "$sitecollectionurl" -Name "ClientDocuments" -Description "Client Docs" -Type "Document Library"

# Output to a new file ( single arrow )
"I am saving this message to a file" > "c:\output.txt"

# Append output to an existing file ( double arrow )
"I am saving this message to a file" >> "c:\output.txt"

Sunday, January 18, 2009

Powershell restricted policy error

Scenario:
I forget to write about it and today when I trying my powershell script on new virtual machine, I got the message that i cant execute this script.

Solution:
Basically, it was because of the fact that out-of-box the default security setting or you can say ExecutionPolicy setting is set to Restricted.

So you need to change it before you can run your script. ( Even if you are Administrator )

Here are some basic commands to check the ExecutionPolicy value, change it to unrestricted and then back to Restricted.

Code:

executionpolicy

set-executionpolicy Unrestricted
Article:
http://www.windowsecurity.com/articles/PowerShell-Security.html

Tuesday, November 4, 2008

Backup site collection using Powershell

Scenario:
You want to backup site collection.

Solution:
You can use Powershell script as an option

Code:

###########################################################
# Script to add function to properly backup site collections
#
# SYNTAX:
# Backup-SPSite
# -url <Site Collection URL>
# -path <path to backup file>
# -lock <"noadditions", "noaccess", "readonly"> #state for backup
# -AdditionalCommands [additional commands for Backup]
# Restore-SPSite
# -url <site collection restore url>
# -path <path to backup file>
# -force
#
# EXAMPLE:
# backup-spsite -url "http://localhost" -path "C:\zbackuptest.bak" -AdditionalCommands "-overwrite"
###########################################################

function global:Backup-SPSite($url,$path,$lock="noaccess",$additionalcommands){
$stsadm = "$env:programfiles\Common Files\Microsoft Shared\Web Server Extensions\12\BIN\STSADM.EXE"

#Check Required Vars
If($url -eq "" -or $url -eq $null ){ Write-Host -ForegroundColor "Red" "URL is required"; return; }
If(!($lock -like "none" -or $lock -like "noadditions" -or $lock -like "noaccess" -or $lock -like "readonly" )){ Write-Host -ForegroundColor "Red" "Lock must be 'none', 'readonly', 'noaccess', or 'noadditions'"; return; }
#Setup Variable Defaults

#LOCK SITE
Write-Progress -Activity "Backup SPSite" -PercentComplete 25 -Status "Locking Site"
$oldlockstate = [xml](&stsadm -o getsitelock -url $url)
$void = &stsadm -o setsitelock -url $url -lock $lock

#BACKUP
Write-Progress -Activity "Backup SPSite" -PercentComplete 50 -Status "Backing up Site ($url)"
$sTemp = &stsadm -o Backup -url $url -filename $path $AdditionalCommands
if(!($sTemp -like "*Operation completed successfully*")){ Write-Host -ForegroundColor "red" -BackgroundColor "white" "Backup of site '$url' Failed! `n $stemp"}

#RESET LOCK STATE
Write-Progress -Activity "Backup SPSite" -PercentComplete 75 -Status "Resetting Site Lock"
$void = &stsadm -o setsitelock -url $url -lock ($oldlockstate.SiteLock.Lock.ToString())
Write-Progress -Activity "Backup SPSite" -PercentComplete 100 -Status "Complete"
}
Article: