The following powershell reads an xml file and adds users to custom SharePoint security groups.
If ([bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544"))
{
write-host "You are an administrator"
}
RegisterSharePointSnapin
$xmlUsersFileFullPath = Join-Path (Get-ScriptDirectory) "xml-config/Users-In-Security-Groups.xml"
$xmlUsers = [xml](get-content $xmlUsersFileFullPath)
[System.Xml.XmlElement] $groupRoot = $xmlUsers.get_DocumentElement()
$tab = "`t"
write-host "Adding users to the following groups..." -ForegroundColor Gray
# Get the site and group names
$web = Get-SPWeb $inputSite
#$web.Name, $web.Title , $web.Url
foreach ($g in $groupRoot.group)
{
[string]$groupLabel = $g.Name
if ($g.HasChildNodes)
{
$groupName = $web.SiteGroups[$groupLabel]
foreach ($u in $g.user)
{
#$gotUser = !([string]::IsNullOrEmpty($u))
$user = $web.Site.RootWeb.EnsureUser($u)
$user
$groupName
$groupName.AddUser($user)
if ($error.count -eq 0)
{
Write-Host "$tab $u Added Successfully to $groupLabel" -ForegroundColor DarkGray;
}
else
{
Write-Host "$tab $u Failed, not added to $groupLabel" -ForegroundColor Red;
}
}
}
}
It works on 'my' machine but on the test farm I get the following error
Exception calling "AddUser" with "1" argument(s): "<nativehr>0x80070005</nativehr><nativestack></nativestack>"
At D:\Deployment\SharePoint\Deploy-Scripts\Add-Users-To-Security-
Groups.ps1:64 char:31
+ $groupName.AddUser <<<< ($user)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
domain\username01 Failed, not added to my-security-groupname
The output from the script confirms its running as an administrator, the $user and $groupName variables hold correct information. The logged in user is a user that has access to Central Admin and successfully runs other deployment scripts that add/remove sharepoint solutions.