Tuesday, July 9, 2013

Change permissions level for the groups in a SharePoint 2010 List or Library

Hi, Recently I needed to breake inherirites for a list on  Sharepoint 2010 site page and change the group permissions to specific one. So here is a powershell script that does the job. You will need to change $OwnerGroupName, $web = Get-SPWeb  $SiteUrl and $list = $web.Lists["<ListName>"]; to your own values.

Task:

Only users in site owner group can have "Full Control"  permissions for specific list on this site. Other groups permissions should be changed to "Read"



What Powershell script does:

1. It breaks inheritance from site
2. Gets all groups on the site
3. Goes via a list role assignments

and

4  If group name is equal to list Role Assignments removes group existing permissions and assign new role with "Read" permissions


Scripts:

[string]$OwnerGroupName = "Owners";

$web = Get-SPWeb  "<SiteUrl>";


$list = $web.Lists["<ListName>"];

$groupCollection =  $web.Groups;

 if ($list -ne $null)
  {
    if (!$list.HasUniqueRoleAssignments)
      {
    $list.BreakRoleInheritance($true);
      }
   $web.AllowUnsafeUpdates = $true;
           foreach ($group in $groupCollection)
{
                Write-Host $group.Name
                if ($group.Name -ne $OwnerGroupName)
                {
                    $roleColl = $list.RoleAssignments
foreach($roleAss in $roleColl){
 
if($roleAss.Member.Name -eq $group.Name){

$permissions = $roleAss.RoleDefinitionBindings
$roleColl.Remove($group)

$roleDef = $web.RoleDefinitions["Read"]
$roleAssign = New-Object Microsoft.SharePoint.SPRoleAssignment($group)
$roleAssign.RoleDefinitionBindings.Add($roleDef)
$list.RoleAssignments.Add($roleAssign)
break
}
}        
    }
}  
$web.AllowUnsafeUpdates = $false;
}

Thursday, May 16, 2013

Add Users to SharePoint Group using PowerShell

$USER_TO_ADD = $null;
 $web = Get-SPWeb -Identity "http://yoursite.com"
$manageGroup = $web.SiteGroups["GroupName"]
 try {
 $adUsername = "$USER_TO_ADD";
 $spUser = $web.Site.RootWeb.EnsureUser($adUsername.Split('\',1));    $manageGroup.AddUser($spUser);
 $manageGroup.Update();
 write-host "User: "
 $spUser.Name "was added to group" }
 catch
 {
    $_ Write-Host $spUser " does not exists"
 }
 } $web.Update(); $web.Dispose();

Thursday, May 9, 2013

Sharepoint 2010 disable event firing using Powershell script



Here is a code:


#Add SharePoint PowerShell SnapIn if not already added
 if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
$web = Get-SPWeb "http://mysharepoint.com/mypage/"


$list = $web.Lists.TryGetList("<ListName>")

$item = $list.Items.GetItemById("<ItemID>")

   try
   {

Write-Host "Deleting" $item.Title;
$myAss = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint");
    $type = $myAss.GetType("Microsoft.SharePoint.SPEventManager");
    $prop = $type.GetProperty([string]"EventFiringDisabled",[System.Reflection.BindingFlags] ([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static));

$prop.SetValue($null, $true, $null);
$prop.GetValue($null,$null)
$item.Title;
     $item.Delete()
    Write-Host  $item.Title "was deleted";

$prop.SetValue($null, $false, $null);
$prop.GetValue($null,$null);
$prop.GetValue(
}
catch
{
     
}

Tuesday, March 26, 2013

Validate the existence of user account in AD using Powershell


Check for user AD account existing with PowerShell script.
Once I needed to check if AD user account exists on server and is enabled.
There are two option to do that.
The first option is to use  Get-ADUser.
Make sure you install the module Active Directory.  


How to install and use Active Directory Module
http://blogs.technet.com/b/heyscriptingguy/archive/2011/08/30/install-active-directory-management-service-for-easy-powershell-access.aspx

The following example shows how to use the function:

Import-Module ActiveDirectory

$AccountName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName].Value ;

$SplitUserName = ($AccountName.Split("\")[1])
$UserExists = Get-ADUser -Filter {sAMAccountName -eq $UserName}
$UserName = $splitusername;
if ($UserExists -eq $null)
{
      Write-Host "User $AccountName does not exist in AD "
}
else 
{
   if (!$UserExists.Enabled)
     {
       Write-Host "User $AccountName is disabled"
     }
     Else
     {
        Write-Host "AD account  $AccountName is ok";
     }
 }
In my case I didn’t have the module Active Directory installed on production server, so I need to find the second way. I couldn’t use the function Get-ADUser from module ActiveDirectory. My opinion is to better to install the module because it has a lot of usefull functions that will makes yourlife easear. I didn’t have such opotunaty because installing module means to restart production server, but this approach I needed to escape, so I found the second option and wrote function.

# function Check-ADUser gets user name as a parametr
# return two properties:
# Status
#              return "0" if AD account doesn't exist in Active directory or was deleted
#              return "1" if the user exists.
# AccountEnable
#              return "0" if AD account is disabled
#          return "1" if AD account is enabled
#Example:
# $UserStatus = (Check-ADUser -Username "testuser1").Status;
# $UserAccountEnabled = (Check-ADUser -Username "$SplitUserName").AccountEnable;
function Check-ADUser
{
Param ($Username)

    $ADRoot = [ADSI]''
    $ADSearch = New-Object System.DirectoryServices.DirectorySearcher($ADRoot);
    $SAMAccountName = "$Username";
$ADSearch.Filter = "(&(objectClass=user(sAMAccountName=$SAMAccountName))";
    $Result = $ADSearch.FindAll();
     
      $Status = "-1";
      $Enabled = "-1";
    if($Result.Count -eq 0)
    { # "No such user on the Server"
        $Status = "0";
    }
    Else
    { #"User exist on the Server"
        $Status = "1";
            foreach ($objResult in $Result)
      {
            $objResult = $objResult.GetDirectoryEntry()
             if ($objResult.accountdisabled)
             {
             #"Account diabled"
             $Enabled = "0";
      }
            else
            {  # "Account enabled"
            $Enabled = "1";
            }
           
      }
    }
    $Results = New-Object Psobject
    $Results | Add-Member Noteproperty Status $Status
      $Results | Add-Member Noteproperty AccountEnable $Enabled
    Write-Output $Results   
}

Example how to use the function Check-ADUser:

$AccountName = $profile[[Microsoft.Office.Server.UserProfiles.PropertyConstants]::AccountName]
.Value 
$SplitUserName = ($AccountName.Split("\")[1])
$UserName = $splitusername;
# check if user exists in AD
$UserExists = (Check-ADUser -Username $SplitUserName).Status;
$UserAccountEnabled = (Check-ADUser -Username $SplitUserName).AccountEnable;

if ($UserExists -ne 1)
 {
   #"User does not exist in AD"
 }
else
 {
   if ($UserAccountEnabled -eq 0)
    {
             #"Account is disabled"
    }
    else
    {
           #"Account is ok"
     }

I hope you will help this information.
Have a good day. :)

Tuesday, February 12, 2013

Create SharePoint Site Quota Templates using PowerShell

Original article

Here you can find PowerShell script that creates and changes Quota Template for Site Collection. You can find full original article here

Create SharePoint Site Quota Templates using PowerShell


function New-SPQuotaTemplate {
<#
    This advanced function creates a new Site Quota Template.
    This function uses .NET code to instantiate an instance of an
    SPQuotaTemplate class. Once the object is created, an instance of the
    SPWebService class is instantiated and the Quota Template is added to the
    Quota Templates Collection.
.Example
    C:\PS>New-SPQuotaTemplate -Name "Custom" -StorageMaximumLevel 2GB -StorageWarningLevel 1GB -UserCodeMaximiumLevel 100 -UserCodeWarningLevel 75
    This example creates an SP Quota Template called Custom with a maximum size
    of 2GB and a warning size of 1GB. Sandboxed solutions are
    limited to 100, with a warning level of 75.
.Example
    C:\PS>New-SPQuotaTemplate -Name "Custom" -StorageMaximumLevel 4GB -StorageWarningLevel 3GB
    This example creates an SP Quota Template called Custom with a maximum size
    of 4GB and a warning size of 3GB
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)][String]$Name,
[Parameter(Mandatory=$true)][Int64]$StorageMaximumLevel,
[Parameter(Mandatory=$true)][Int64]$StorageWarningLevel,
[Parameter(Mandatory=$false)][System.Double]$UserCodeMaximumLevel,
[Parameter(Mandatory=$false)][System.Double]$UserCodeWarningLevel
)
# Instantiate an instance of an SPQuotaTemplate class #
Write-Host "Instantiating an instance of an SPQuotaTemplate class"
$Quota = New-Object Microsoft.SharePoint.Administration.SPQuotaTemplate
# Set the Properties #
Write-Host "Setting properties on the Quota object"
$Quota.Name = $Name
$Quota.StorageMaximumLevel = $StorageMaximumLevel
$Quota.StorageWarningLevel = $StorageWarningLevel
$Quota.UserCodeMaximumLevel = $UserCodeMaximumLevel
$Quota.UserCodeWarningLevel = $UserCodeWarningLevel
# Get an Instance of the SPWebService Class #
Write-Host "Getting an instance of an SPWebService class"
$Service = [Microsoft.SharePoint.Administration.SPWebService]::ContentService
if ($Service.QuotaTemplates[$Name] -eq $null )
{
# Use the Add() method to add the quota template to the collection #
Write-Host "Adding the $($Name) Quota Template to the Quota Templates Collection"
$Service.QuotaTemplates.Add($Quota)
# Call the Update() method to commit the changes #
$Service.Update()
}
else
{
Write-Host "Quota Template $Name exists"
}
}

To change the quota template for a site collection by using Windows PowerShell

function Set-SPQuotaTemplate ($SiteCollectionName,$QuotaTemplateName)
{
    Set-SPSite -Identity $SiteCollectionName -QuotaTemplate $QuotaTemplateName 
Write-Host "Quota template $QuotaTemplateName was set to site collection $SiteCollectionName"
}

Tuesday, January 8, 2013

Display more than 50 items in SharePoint menu



Recently I had a ticket where SahrePoint site owner wanted to add more then 51 sites to the SharePoint and the problem was that 51th site wasn't showed in the Left navigation and Site Setting > Navigation.

After I changed the web.config of the applications everything work, so please post below to resolve the issue.

SharePoint navigation is based on the ASP.NET 2 SiteMap Provider. By default the limit is 50 items per menu.


1. Open web application  web.config in C:\inetpub\wwwroot\wss\VirtualDirectories\<yourwebapp>
2. If you need to change the limit, justadd the DynamicChildLimit attribute to the GlobalNavSiteMapProvider, CombinedNavSiteMapProvider, CurrentNavSiteMapProvider and CurrentNavSiteMapProviderNoEncode nodes and specify the limit e.g. 100:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<configuration>
  ...
  <system.web>
    ...
    <siteMap defaultProvider="CurrentNavSiteMapProvider" enabled="true">
      <providers>
        ...
        <add name="GlobalNavSiteMapProvider" ... DynamicChildLimit="100" />
        <add name="CombinedNavSiteMapProvider" ... DynamicChildLimit="100" />
        <add name="CurrentNavSiteMapProvider" ... DynamicChildLimit="100" />
        <add name="CurrentNavSiteMapProviderNoEncode" ... DynamicChildLimit="100" />
        ...
    </providers>
    </siteMap>
    ...
  </system.web>
  ...
</configuration>

3. Restart iis




Thursday, December 13, 2012

SharePoint 2010 Feature activation and disabling with PowerShell script

The script activates a feature with ID 00BFEA71-EB8A-40B1-80C7-506BE7590102 at a web site under “YourServer/Sites/” site collection

Feature activation:

Enable-SPFeature "00BFEA71-EB8A-40B1-80C7-506BE7590102" -Url http://YourServer/Sites/testsite

Feature disabling:

Disable-SPFeature "00BFEA71-EB8A-40B1-80C7-506BE7590102" -Url http://YourServer/Sites/testsite

Note!!!

The feature must be already deployed and installed, the scripts just activating  and disabling the feature.