2

I have an issue where I am trying to handle the error but could not get it done. here is the code:

$UserSPU = "domain\user"
$site = Get-SPSite http://siteurl
$web = $site.OpenWeb()
$user = $web.EnsureUser($UserSPR)

The above code works well if I have a valid user, But it throws the error when a user is not valid. But what I am trying to get is If a user is not valid then throws my custom errors. This is what i am trying to do but it is not working as expected and throws the error before wrtie-host and exit.

If(!($web.EnsureUser($UserSPR)))
 {
Write-Host  $UserSPR " account is not valid"
}

Please guide me or fix the above code.

4

Try:

Add-PSSnapin Microsoft.SharePoint.PowerShell -EA 0 
$UserSPU = "domain\user"
$site = Get-SPSite https://sharepoint.example.com
$web = $site.OpenWeb()

try
{
    $user = $web.EnsureUser($UserSPR)
}
Catch
{
    Write-Host 'User not found.'
}
  • And if I want exit from here then should I type return;? – Waqas Sarwar MVP Apr 21 '16 at 22:47
  • 1
    That will return from a function. break is the other keyword (to exit a loop) or continue (to exit the current iteration of the loop but continue looping). – Trevor Seward Apr 21 '16 at 22:48
  • I want exit from program – Waqas Sarwar MVP Apr 21 '16 at 22:49
  • 1
    exit will exit the script as well as the PowerShell session. – Trevor Seward Apr 21 '16 at 22:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.