?
Solved

powershell - check for exisiting AD User

Posted on 2016-10-19
4
Medium Priority
?
87 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 85

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 600 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 85

Accepted Solution

by:
oBdA earned 1400 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
In the absence of a fully-fledged GPO Management product like AGPM, the script in this article will provide you with a simple way to watch the domain (or a select OU) for GPOs changes and automatically take backups when policies are added, removed o…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

764 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