Home > Back-end >  find User in a list of servers PowerShell
find User in a list of servers PowerShell

Time:05-05

I have a list of servers where I have to find a specific user 'adtuser', and if it is part of the admin group in each server, and output a text file.

For the moment I have this script and it partially works.
I have the desired output, but some server are missing (they are ok if you check individually) and the script require a lot of time.

Thanks in advance

Get-Content C:\servers.txt | ForEach-Object {
    if (-not (Test-Connection -ComputerName $_ -Count 1 -Quiet)) {
        Write-Warning "Server '$_' is Unreachable hence Could not fetch data"
        return
    }
    
    $computer = $_
    ([adsi]"WinNT://$_").Children.ForEach{ 
        if($_.SchemaClassName -ne 'user' -and $_.Name.Value -ne 'ADTuser') {
            return
        }
        
        $groups = $_.Groups().ForEach([adsi]).Name
        
        [pscustomobject]@{
            Computername = $computer
            UserName     = $_.Name.Value
            Memberof     = $groups -join ';'
            Status       = $groups -contains 'Administrators'
        }
    }
} | Out-File -FilePath C:\users.txt

CodePudding user response:

Be advised that test-netconnection requires powerhshell 2.0 or better.

As @Santiago mentioned — I’m using Test-Connection with -port 3389 to test against the Windows RDP port. OP was originally just testing for ICMP connectivity which is a poor test because of common firewall rules.

You could test any know Windows port but RDP is usually pretty safe to assume is open. NMAP (or you network admin …grin) could probably give you the best guidance.

#!/usr/bin/env powershell
$servers = Get-Content -Path $env:HOMEDRIVE/servers.txt

ForEach ($_ in $servers) {
    if (-not (Test-NetConnection -ComputerName $_ -Port 3389)) {
        Write-Warning -Message ("Server '{0}' is Unreachable hence Could not fetch data" -f $_)
        return
    }
    
    $computer = $_
    ([adsi]('WinNT://{0}' -f $_)).Children | Foreach-Object { 
        if($_.SchemaClassName -ne 'user' -and $_.Name.Value -ne 'ADTuser') {
            return
        }
        
        $groups = $_.Groups() | Foreach-Object [adsi].Name
        
        New-Object -TypeName PSObject -Property @{
            Computername = $computer
            UserName     = $_.Name.Value
            Memberof     = $groups -join ';'
            Status       = $groups -contains 'Administrators'
        }
    } | Out-File -FilePath $env:HOMEDRIVE/users.txt -Append
} 
  • Related