I'm often asked to add a large number of people to a SharePoint group. I'm never given the account names - instead, people often copy and paste from Outlook. This is almost always in the following format:
Surname, Firstname; Surname, Firstname;
The same formatting is used in the SharePoint environment. What I've done for small numbers of people is to use the standard SharePoint built-in web interface, but this is limited to 256 characters at a time, and is rather slow when working with more data than that. So, I wrote two PowerShell scripts. The first converts semicolon-seperated values into an entry on each line.
$x = ''
$x = Get-Content "SemicolonUsers.txt"
$x.replace("; ","`r`n") | out-File "Users.txt"
Quite simple, probably better ways of doing this, but it'll do for now. Then, the other PowerShell script does the actual work, and outputs errors to Errors.log.
$SiteURL = "http://sharepoint/sitename"
$GroupName = "SharePoint Group Name"
$UserNames = "Users.txt"
function WriteOutputError($message)
{
$host.UI.RawUI.ForegroundColor = "red"
Write-Output($message)
$message |Out-File Errors.log -Append
$host.UI.RawUI.ForegroundColor = "white"
}
function ConvertUser($user)
{
$date = Get-Date -format T
$search = New-Object DirectoryServices.DirectorySearcher([ADSI]“”)
$search.filter = “(&(objectClass=user)(displayName=$user))”
$results = $search.Findall()
$count = $search.Findall().Count
if($count -ne 1) {
WriteOutputError('' + $date + ': ' + $count + ' results found for ' + $user + ': cannot add.')
}
else {
foreach($result in $results)
{
$userEntry = $result.GetDirectoryEntry()
### We still have multiple inactive domains, so focus only on the current domain
$accountName = "DOMAIN\" + $userEntry.sAMAccountName | Out-String
#Write-Output($date + ': Adding ' + $accountName)
WriteOutputError(Set-SPUser -Web $SiteURL -Group $GroupName -Identity $accountName)
}
}
}
function ConvertUsers
{
process
{
foreach($user In $_)
{
ConvertUser($user)
}
}
}
$date = Get-Date -format T
WriteOutputError('--------------------------------------')
WriteOutputError('' + $date + ": Starting new instance of AddUsers.")
WriteOutputError('' + $date + ": SiteURL: " + $SiteURL)
WriteOutputError('' + $date + ": GroupName: " + $GroupName)
WriteOutputError('--------------------------------------')
$host.UI.RawUI.ForegroundColor = "white"
Get-Content $UserNames | ConvertUsers
$date = Get-Date -format T
WriteOutputError('--------------------------------------')
WriteOutputError('' + $date + ': Operation completed.')
WriteOutputError('--------------------------------------')
$host.UI.RawUI.ForegroundColor = "gray"
No comments:
Post a Comment