Wednesday 13 April 2016

SharePoint On-Prem : Set-SPUser error

A - OBJECTIVE: 

An admin is supposed to add one user to all subsites across all site collections within a web application.

B - PROBLEM:

When executing the script Set-SPUser to add the user. Although the user can be added to some subsites, you may encounter this problem at other sites:
Set-SPUser : You must specify a valid user object or user identity.
At line:6 char:1
+ Set-SPUser -Identity "i:0#.w|domain\jon" -SyncFromAD -Web $temp -AddPermissio ...
+                                                                  ~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Set-SPUser], PSArgumentException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletSetUser


 
C - SOLUTION:

Set-SPUser command is correct, however, because the particular user has not visited these sites (e.g. student09 in the above example). Hence, SharePoint cannot resolve the user properly.

You are supposed to add that user as a site collection administrator first as a work-around, run the script, and remove the user out of the site collection admin group

D - SOURCE CODE:

############## POWERSHELL SCRIPT
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$output = "C:\GrantPermissions-Jon.csv"
Add-Content $output "WEB URL"
# Get all sites
$SPSites = Get-SPWebApplication "http://shareuat" | Get-SPsite -Limit all 
foreach($customSPSite in $SPSites){
    # grant the permission at the rootweb level
    $temp = $customSPSite.URL
    $temp
    Add-Content $output $temp
    Set-SPUser -Identity "i:0#.w|domain\jon" -SyncFromAD -Web $temp -AddPermissionLevel "Read"   
   
    # Get all websites
    $customSPWebs = $customSPSite | Get-SPWeb -Limit all | Where { $_.HasUniquePerm -AND $_.ParentWeb -NE $Null }
        foreach ($customSPWeb in $customSPWebs){
            $temp2 = $customSPWeb.URL
            $temp2
            Add-Content $output $temp2
            Set-SPUser -Identity "i:0#.w|domain\jon" -SyncFromAD -Web $temp -AddPermissionLevel "Read"
    }
}

No comments:

Post a Comment