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

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


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

        echo "Disposing web"
        echo "Disposing site"

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?


  • 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.