0

Below is my code to add the user to the permission group.

function SetUserIntoGroup{
    param([string]$WebUrl)
    $WebUrl
    $ADGroupName = "AD Group Name"
    $SPGroupName = "Project Owners"
    echo "Function Called"
    $site = Get-SPSite $WebUrl
    $web = $site.OpenWeb()
    $web.AllowUnsafeUpdates = $true

    try{

        $user = $web.EnsureUser($ADGroupName)
        $user.Name
        $user.LoginName
        if(@($web.SiteGroups.GetCollection(@($SPGroupName))).Count -eq 1){
            echo "Group Found"
            $SPGroup1 = $web.SiteGroups[$SPGroupName]
            $SPGroup1.Name
            # Check if user does not exist in group then only add to the group.
            $SPGroup1.AddUser($user)
            Write-Output "$user added to $SPGroup"
        }
    }
    catch [Exception]{
      Write-Host $_.Exception.GetType().FullName, $_.Exception.Message -foregroundcolor "magenta"
    }
    finally{
        $web.AllowUnsafeUpdates = $false

        if($web){
        echo "Disposing web"
        $web.Dispose();
        }
        if($site){
        echo "Disposing site"
        $site.Dispose();
        }
    }
}

However, it does not give me the error when I run the code. It sometimes adds the user to the permission group and sometimes does not add. I can't figure out what is the exact scenario when it does not work. If I run multiple times then I get the user added to the group.

Please help me to solve the issue. One more thing, is the code written in good approach or needs to be modified?

TIA.

  • It appears to not find the group in "if(@($web.SiteGroups.GetCollection(@($SPGroupName))).Count -eq 1){". Can you just omit that IF check, I think it will not throw error in case user already exists in a group so that IF might not be necessary. – Jussi Palo Jan 3 '18 at 11:15
  • Okay, I will check with suggested changes and let you know. – users1100 Jan 3 '18 at 11:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.