Solved

powershell - check for exisiting AD User

Posted on 2016-10-19
4
36 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

[Webinar] Disaster Recovery and Cloud Management

Learn from Unigma and CloudBerry industry veterans which providers are best for certain use cases and how to lower cloud costs, how to grow your Managed Services practice in IaaS clouds, and how to utilize public cloud for Disaster Recovery

Question has a verified solution.

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

The article will show you how you can maintain a simple logfile of all Startup and Shutdown events on Windows servers and desktops with PowerShell. The script can be easily adapted into doing more like gracefully silencing/updating your monitoring s…
How to sign a powershell script so you can prevent tampering, and only allow users to run authorised Powershell scripts
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

867 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now