Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am trying to create a script to add a user to an existing SharePoint group. I'm new to PowerShell Scripting & SharePoint, so I'm a little lost. I keep getting the error that the specified group does not exist, even though I'm looking at the created group under the Site Settings -> Groups page.

What am I doing wrong?

#Add SharePoint PowerShell SnapIn if not already added
 if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
 Add-PSSnapin "Microsoft.SharePoint.PowerShell"
 }

Write-Output "Starting process"

$site = Get-SPSite 'http://spdev:36600'
$user = Get-SPUser -web $web -Identity DOMAIN\username
$rootWebGroups = $site.RootWeb.groups

Write-Output "Site: $site"
Write-Output "User: $user"

foreach ($web in $websites){
    $group = $web.sitegroups['PowerShell AddUser Test Group']

    Write-Output "Current website: $web"
    Write-Output "Group:: $group"
    Write-Output ""
    try {
        Set-SPUser -Identity $user -Web $web -Group $group   
        Write-Output "$user added to $group"   
    } catch {
        Write-Output "$user could not be added to $group"
    }
}


Write-Output "Finishing up"

And the error I am getting:

Set-SPUser : The specified group does not exist.
At line:27 char:19
+         Set-SPUser <<<<  -Identity $user -Web $web -Group $group.Name
    + CategoryInfo          : InvalidArgument: (:) [Set-SPUser], PSArgumentNullException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletSetUser

I did find a way that works by using $web.sitegroups['PowerShell AddUser Test Group'].AddUser($user) instead of #Set-SPUser -Identity $user -Web $web -Group $group, but I still don't understand why the previous code did not work.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

If you look at the TechNet page for the Set-SPUser commandlet it seems that you are providing it with a string but that is not the expected type.

Group - Optional - Microsoft.SharePoint.PowerShell.SPGroupPipeBind Adds the user to an existing group in the given site.

http://technet.microsoft.com/en-us/library/ff607827.aspx

Try getting a handle on the group and then passing that variable as the argument.

And a +1 on your question for using Write-Output and not Write-Host.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.