Lotzi11
Lotzi11

Reputation: 549

Issues with [ADSI]::Exists

I'm trying to figure out if a user exists before I attempt to delete it. I found this command and tried to implement it into my script. I notice however, that the command will return true any username I typed into it, whether it exist or not. Can someone help explain to me the proper way of using this script, or can someone show me a better way of determining if a user exists?

[ADSI]::Exists("WinNT://Lotzi")

The following code should fail b/c Lotzi is not an actual user, but the command will return true.

Upvotes: 0

Views: 2190

Answers (2)

postanote
postanote

Reputation: 16096

You don't need to use ADSI, that's the old way. Well, you can, but just saying.

Use the PowerShell AD cmdlets?

# Get parameters, examples, full and Online help for a cmdlet or function

(Get-Command -Name Get-ADUser).Parameters
Get-help -Name Get-ADUser -Examples
Get-help -Name Get-ADUser -Full
Get-help -Name Get-ADUser -Online


(Get-Command -Name Get-ADComputer).Parameters
Get-help -Name Get-ADComputer -Examples
Get-help -Name Get-ADComputer -Full
Get-help -Name Get-ADComputer -Online

That is why they exist. Now you need to either download and install or just install the Windows RSAT tools on your workstation...

https://support.microsoft.com/en-us/help/2693643/remote-server-administration-tools-rsat-for-windows-operating-systems

... or remote to a domain controller to use the AD cmdlets.

How To Use The 2012 Active Directory PowerShell Cmdlets From Windows 7 https://blogs.technet.microsoft.com/ashleymcglone/2013/06/27/how-to-use-the-2012-active-directory-powershell-cmdlets-from-windows-7

Then just do something like this...

$Users = 'TestUser001','TestUser001','TestUser001'
ForEach($User in $Users)
{ 
    $User = $(try {Get-ADUser 'TestUser001'} catch {$null})
    if ($User -ne $null) {
      # Exists
    } else {
      # Doesn't Exist
      Write-Warning -Message "User $User not found"
    }
}

$Computers = 'Computer001','Computer001','Computer001'
ForEach ($Computer in $Computers)
{ 
    $Computer = $(try {Get-ADUser 'TestUser001'} catch {$null})
    if ($Computer -ne $null) {
      # Exists
    } else {
      # Doesn't Exist
      Write-Warning -Message "Computer $Computer not found"
    }
}

Upvotes: 0

Bill_Stewart
Bill_Stewart

Reputation: 24565

Here's one quick way to check whether a specific account exists in Active Directory:

$accountName = "testname"
$searcher = [ADSISearcher] "(sAMAccountName=$accountName)"
$accountExists = $searcher.FindOne() -ne $null

Upvotes: 1

Related Questions