Solved

powershell - check for exisiting AD User

Posted on 2016-10-19
4
48 Views
Last Modified: 2016-10-19
Very simple powershell function (part below) . No matter what the $username variable is I always get the message 'User already exists'. Obviously I am trying with nonsense usernames that definitely don't exist as well as those that do. what's going on?

-----

Function CreateStaff ()
{
# Check if an AD User of that name already exists
$ADUserCheck = get-aduser -Identity $username -ErrorAction SilentlyContinue

    If ($ADUserCheck -eq $null)
      {
        Write-Host "User does not already exist, creating staff user..."
      }
     
    Else
      {
      Write-Warning "$username already exists"
      }
}
0
Comment
Question by:Pete
  • 2
4 Comments
 
LVL 83

Expert Comment

by:oBdA
ID: 41850215
When a cmdlet errors out, it returns nothing, not $Null, so ($ADUserCheck -eq $null) will always be $False.
Just drop the "-eq $Null" and reverse the logic:
Function CreateStaff () {
	# Check if an AD User of that name already exists
	$ADUserCheck = Get-ADUser -Identity $username -ErrorAction SilentlyContinue
    If ($ADUserCheck) {
		Write-Warning "$username already exists"
	} Else {
		Write-Host "User does not already exist, creating staff user..."
	}
}

Open in new window

0
 
LVL 1

Author Comment

by:Pete
ID: 41850235
OK, now when I enter a unique username (so it should create a user) I get the error:

---

get-aduser : Cannot find an object with identity: 'thisisausername' under: 'DC=domain,DC=LOCAL'.
At .ps1:190 char:16
+ ... UserCheck = get-aduser -Identity $username -ErrorAction SilentlyConti ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (SDFSDFSDFSDFS:ADUser) [Get-ADUser], ADIdentityNotFoundException
    + FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundExcep
   tion,Microsoft.ActiveDirectory.Management.Commands.GetADUser
0
 
LVL 40

Assisted Solution

by:Subsun
Subsun earned 150 total points
ID: 41850244
Using -ErrorAction SilentlyContinue may not suppress the error, use Try catch method, and you also need to define a parameter.
Function CreateStaff ($Username) {
	$ADUserCheck = Try {Get-ADUser -Identity $username}Catch{}
    If ($ADUserCheck) {
		Write-Warning "$username already exists"
	} Else {
		Write-Host "User does not already exist, creating staff user..."
	}
}

CreateStaff UserA

Open in new window

Or use Filter or LDAPFilter
$ADUserCheck = Get-ADUser -LDAPFilter "(sAMAccountName=$Username)"

Open in new window

0
 
LVL 83

Accepted Solution

by:
oBdA earned 350 total points
ID: 41850265
Catch (only) the ADIdentityNotFoundException, in case something else in AD isn't working:
Function CreateStaff () {
	# Check if an AD User of that name already exists
	Try {
		$ADUserCheck = Get-ADUser -Identity Bla -ErrorAction SilentlyContinue
	} Catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {
	}
    If ($ADUserCheck) {
		Write-Warning "$username already exists"
	} Else {
		Write-Host "User does not already exist, creating staff user..."
	}
}

Open in new window

0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This script checks a path to see if a folder exists. If the folder does exist you will get output "The folder has previously been created. No action taken" If not it will create the folder. Then adds one user modify permission to the folder. It …
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question