0

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.

Lotzi11
  • 477
  • 1
  • 13
  • 26

2 Answers2

1

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
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
  • Yes; just append a `$` character to the computer's name (a computer account's `sAMAccountName` attribute is the computer's name with a `$` character suffix). – Bill_Stewart Feb 05 '18 at 20:46
  • In the above example, you would search for `testname$` instead of just `testname` (for a computer named `testname`). – Bill_Stewart Feb 05 '18 at 20:51
0

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"
    }
}
postanote
  • 15,138
  • 2
  • 14
  • 25