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.