Hi,
I want to remove a list of users from all SP groups, however im getting the following errors for most of the cases:
In some cases: Exception calling "RemoveUser" with "1" argument(s): ""
On others: Exception calling "EnsureUser" with "1" argument(s): ""
And i cannot figure out why. Can someone help?
Script:
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Import-Module ActiveDirectory
Function Get-UserAccount($DisplayName)
{
$UserAccount = Get-ADUser -LDAPFilter "(displayName=$DisplayName)"
if($UserAccount.sAMAccountName -ne $null -and $UserAccount.Enabled -eq $true)
{
return $UserAccount.sAMAccountName.tostring()
}
else
{
return $null
}
}
Function RemoveUser-FromAllGroups($web, $SiteURL, $login)
{
#Get the User to Remove
$User = $web.EnsureUser($login)
#Iterate through all Groups
foreach($Group in $web.Groups)
{
$GroupUser = $Group.Users | where {$_.UserLogin -eq $User.UserLogin}
#Check if user member of the group
if($GroupUser -ne $null)
{
$Group.RemoveUser($GroupUser)
Write-Host "$($GroupUser) Removed from the Group: $($Group)"
#"$User Removed from the Group: $Group" | out-file -filepath $OutComplete -Append
}
}
}
#Variables
$URL = "https://xxxxx-xxxx.altran.de"
$file = Import-Csv -Path "D:\Scripts\UserList.csv"
$OutComplete = "D:\Scripts\OutComplete.txt"
####### Start Main Logic #######
$web = Get-SPWeb -Identity $URL
$file | ForEach-Object {
$DisplayName = $_.FamilyName + " " + $_.FirstName
$UserAccount = Get-UserAccount $DisplayName
if($UserAccount -ne $null)
{
Write-Host "Account found for: "$DisplayName -f Green | out-file -filepath $OutComplete -Append
"Account found for: " + $DisplayName | out-file -filepath $OutComplete -Append
$login = "i:0#.w|xxxxx\" + $UserAccount
RemoveUser-FromAllGroups $web $URL $login
#Remove-RoleAssignments $web $login
}
else
{
write-host "No matching User Account Found for :"$DisplayName -f Red
"No matching User Account Found for :" + $DisplayName | out-file -filepath $OutComplete -Append
}
}
Rui Pais