Powershell function to check if Active Directory users exists

Here is a little powershell function I made to see check if specific active directory users exists or not.

function userExists ([string]$name){
    #written by: √ėyvind Nilsen (oyvindnilsen.com)
    [bool]$ret = $false #return variable
    $domainRoot = [ADSI]''
    $dirSearcher = New-Object System.DirectoryServices.DirectorySearcher($domainRoot)
    $dirSearcher.filter = "(&(objectClass=user)(sAMAccountName=$name))"
    $results = $dirSearcher.findall()

    if ($results.Count -gt 0) { #if a user object is found, that means the user exists.
        $ret = $true

    return $ret

userExists batman

#Example 2:
if(userExists batman) {
   write-host "the user exists"
} else {
   write-host "the user does not exist"
Posted in Scripting | Tagged , , , , , , , , , | Leave a comment

One line in powershell to check if remote port is open

Here is an easy way to use powershell to see if a remote machine is listening on a specific port. If the command finishes without returning anything the remote machine is listening on the port. If the commands times out or return an error the machine does not listen on that port or your request was blocked by an firewall or ACL rule.


#Check TCP connection
(New-Object Net.Sockets.TcpClient).Connect("<remote machine>",<port>)

#Check UDP conection
(New-Object Net.Sockets.UdpClient).Connect("<remote machine>",<port>)
Posted in Scripting | Tagged , , , , , , , , , , , | 1 Comment