Accepted way to return a value

Hi there,

My co worker one time did this kind of stuff :

$error = $false
try
{
       $Object = Get-aduser -Identity  Peter -erroraction stop
}

catch
{
           $Error = $true
}

I like this code and wanted to use it in a function that returns true or false for an existing aduser. But it could be anything.

function Test-AduserExistance($UserName)
{
$error = $false
try
{
       $Object = Get-Aduser -Identity $Username -ErrorAction stop
}

catch
{
           $Error = $true
}

write-output $Error
}

Could we use this kind or am I missing something or would an other way be better ? We also want to use this kind of thing if resourcegroups are missing in Azure.

Thx!

Jona

Just google it, there are plenty on the web and even one-liners.

https://www.google.com/search?q=check+if+ad+user+exists+powershell

Thank you.

Hi thank you but my question is not whether it works it does, my question is : Is this a valid way. It’s more of a question like. Is this an ugly or not ugly solution.

 

Thank you in advance anyone!

 

Jona

That’s a very explicit and verbose way to do it, yes. I personally would simplify it like this.

function Test-AduserExistence($UserName)
{
    [bool](Get-Aduser -Filter "name -like '*$Username*'")
}

or if you want to check against samaccountname

function Test-AduserExistence($UserName)
{
    [bool](Get-Aduser -Filter "samaccountname -like '*$username*'")
}

Or if you wanted to check either

function Test-AduserExistence($UserName)
{
    [bool](Get-Aduser -Filter "name -like '*$Username*' -or samaccountname -like '*$username*'")
}

If there is a value produced (meaning a user was found) then the cast to [bool] will be $true otherwise it will be $false

@JonaUK - $Error is an in-built variable in PowerShell and we should not set value to it.

Using Try Catch is a good option, but we should be checking the exception as well before setting the Flag, There can be many reasons why Get-ADUser fails.

Check this out:

https://www.powershellmagazine.com/2013/08/15/pstip-validate-if-a-user-exists-in-active-directory/

Also, I’d just mention that wrapping this is a function is just unnecessary code. There are multiple one line checks for a boolean, so just make a descriptive variable:

[bool]$userExists = (Get-Aduser -Filter "name -like '*$Username*'")

Yes thank you both of you this so much clarifies things for me!

How would we check a specific error? Of course I can google it, but I like some expert answer.

Thx so much!

 

Jona

Errors do print the exception by default until PS 5.1 and with Get-Error in PowerShell core we will get all the necessary information from errors.
So when catching the exception you can specify the exception type to catch block.

try{
 some unknown keyword
}
catch [DivideByZeroException]{
  'division by zero not possible'
}
catch [exception] {
  'Error for unknown keyword'
}

try{
 1/0
}
catch [DivideByZeroException]{
  'division by zero not possible'
}
catch [exception] {
  'Error for unknown keyword'
}

Just one question, if I used the correct exception, is this a valid Function using try and catch?

 

thx

 

Jona

It’s not really a question of validity. If the code executes it’s valid. Using -Identity with Get-ADUser will produce an error. Using -Filter either finds a result or nothing\null. There is strict and minimal. Look at these examples:

# 1 line. Simple and has the same functionality of the function wrapper
[bool](Get-Aduser -Filter "samaccountname -like '*$username*'")

#3 lines. Not really gaining anything
function Test-AdUserExistence($UserName) {
    [bool](Get-Aduser -Filter "samaccountname -like '*$username*'")
}
# 10 lines. More strict. Mandatory parameter
function Test-AdUserExistenceV2 {
    param (
        [Parameter(Mandatory=$true)]
        [string]$UserName
    )
    begin {}
    process {
        [bool](Get-Aduser -Filter "samaccountname -like '*$username*'")
    }
    end {}
}

# More traditional approach.  Once you find the user you are going to do
# something with the user, so the search returns the user vs just telling
# you the user exits
$user = Get-ADUser -Filter {SamAccountName -eq $UserName}

if ($user) {
    try {
        Set-ADUser -Identity $user -ErrorAction Stop
    }
    catch {
        Throw ('Error occured setting AD stuf for {0}. {1}' -f $UserName,$_)
    }
}
else {
    'No user found with username {0}' -f $UserName
}