简体   繁体   中英

How to create an exception list for LDAP query in Powershell combined with an Get-ADComputer

I have a script that searches all machines in a domain and is pulling details about them and presents them in a report.

    ipmo ActiveDirectory  ;
    $ADSearchBase = "DC=contoso,DC=chelu,DC=ro,DC=com"  


        write-host 
        write-host "Preparing your data..."
        write-host 

$AD_Results = Get-ADComputer -filter '(Enabled -eq $true)' -SearchScope Subtree -SearchBase $ADSearchBase -properties Description, PasswordNeverExpires, LastLogonTimeStamp, PasswordLastSet, operatingSystem, operatingSystemServicePack, whenCreated, distinguishedname, canonicalname
$count = $AD_Results.count
"Analyzing $count machines..."

# MAIN LOOP

ForEach ($Result In $AD_Results)
{
        $i++ 
        if ($i % 16 -eq 0)  { $i }

        $ComputerName=$result.name
        $OS = $result.operatingSystem
        $DESC =  $result.Description
        $DN =  $result.distinguishedname

        $PNE = $result.passwordneverexpires

        if  ($ComputerName.Length -ge 15)
         {
            $ComputerName = $ComputerName.substring(0,15)
         }


     ## BEGIN TIME CONVERSIONS
        $LLTS = 0       #AD LastLogonTimestamp
        $PLS = 0        #AD PasswordLastSet

         If ($result.lastLogonTimeStamp -eq $Null)
          {
            $T = [Int64]0
          }
          Else
          {
            $T = [DateTime]::FromFileTime([Int64]::Parse($result.lastlogontimestamp)).ToString("dd/MM/yyyy HH:mm:ss")  
          }
               $LLTS = $T 

       $WCR = $result.whencreated.ToString("dd/MM/yyyy HH:mm:ss")


          If (!($result.passWordLastSet -eq $Null))
          {
               $PLS = $result.passwordLastSet.ToString("dd/MM/yyyy HH:mm:ss")
          }
      ## END TIME CONVERSIONS


# 1/2 is in Exceptions?

        if ($DN -match "Domain Controllers") {"$computername : DOMAIN CONTROLLER -> Skipping..." ; $Skipped++ ; continue}
        if ($DN -match "HVCL") {"$computername : Virtual Cluster Name -> Skipping..." ; $Skipped++ ; continue}  


        #2/2: isWin? 

         if ($result.operatingSystem -notlike '*windows*') 
         {
          $Skipped++
          continue
         }

          $isServer=0
         if (($DN -match "Servers") -or ($result.operatingSystem -like '*server*')) 
          {$isServer=1}

The script is skipping some machines based on their DN (distinguishedname) as it can be seen in the "# 1/2 is in Exceptions?" and in "#2/2: isWin?"

Meanwhile I got a request from a user to except some other (extra) machines that cannot be sorted using the initial query in the AD, which is:

$AD_Results = Get-ADComputer -filter '(Enabled -eq $true)' -SearchScope Subtree -SearchBase $ADSearchBase -properties Description, PasswordNeverExpires, LastLogonTimeStamp, PasswordLastSet, operatingSystem, operatingSystemServicePack, whenCreated, distinguishedname, canonicalname

Basically the user wants to except from the report some specific machines (machine1, machine2, machine3) which are not real computer accounts but "connection points" for clustered resources. Now, there are 2 ways to do that:

  1. To use a script to find all these"connection points" for clustered resources. The only way to detect CNO and VCO is to look at "Service Principal name" attribute from the computer object. If you find "MSClusterVirtualServer" then the object is a CNO or a VCO

    Here is what I could come up with:

     $serviceType="MSClusterVirtualServer" $spns = @{} $filter = "(servicePrincipalName=$serviceType/*)" $domain = New-Object System.DirectoryServices.DirectoryEntry $searcher = New-Object System.DirectoryServices.DirectorySearcher $searcher.SearchRoot = $domain $searcher.PageSize = 1000 $searcher.Filter = $filter $results = $searcher.FindAll() foreach ($result in $results){ $account = $result.GetDirectoryEntry() foreach ($spn in $account.servicePrincipalName.Value){ if($spn.contains("$serviceType/")){ $spns[$("$spn`t$($account.samAccountName)")]=1; } } } $spns.keys | sort-object 
  2. To actually create a "whitelist" or "blacklist" where to include machines by names, assuming that in the future some other users might come up with similar requests to except machines from showing up in the report, and that these last machines might not be Virtual Clusters. I prefer this method. What I did is to create an LDAP filter to find that 3 specific machines. Here it is:

      (&(&(&(objectCategory=computer)(objectClass=computer)(|(cn=machine1)(cn=machine2)(cn=machine3))))) 

QUESTION: Can you help me put together an IF clause that will point towards a "whitelist" in csv format that will contain the names list of the machines to be excepted from the report? The whitelist should reside on the same folder where the script is residing. Should I use the above LDAP filter? How do I do that?

Based on your $AD_Result I would try something along these lines:

ForEach ($exception In (Get-Content "exceptions.txt")) {
   $AD_Result = $AD_Result | ? { $_.Name -ine $exception }
}

Why did you want your exceptions file in csv format?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM