I am using following PS script to add users from a text file. Some of the users in the text file are inactive or gone (basically can't be resolved). The error message from the catch block is executed for all the users. If invalid user then it should display $spUser does not exists. Can anyone see what am I doing incorrect here? Just wanted to mention that valid AD users are getting added. EnsureUser is throwing exception when user not found in AD.
$webUrl = "http://server"
$web = Get-SPWeb $webUrl
$fileWithPath = "N:\Staging\Users.txt"
$content = Get-Content $fileWithPath
$spGroup = "Northwest Region Sales"
$rd="Read"
foreach($user in $content)
{
try
{
$spUser = $web.EnsureUser($user)
if($spUser -ne $null)
{
Write-Host $spuser
Write-Host "Adding " $spUser
$web.SiteGroups[$spGroup].AddUser($spUser)
Write-Host $user " User added to the group successfully"
}
else
{
Write-Host $spUser " does not exists"
}
}
catch
{
Write-Host "Error occured on " $user
}
}
$spGroup = $web.SiteGroups[$spGroup]andWrite-Host $spGroupto see if group is found – Vedran Rasol Oct 4 '11 at 21:01EnsureUserthrows exception if user is not found. If exception is thrown then user don't exist so you write 'does not exist' and foreach loop will continue. You can remove if statement because it is useless. – Vedran Rasol Oct 4 '11 at 21:30