find out in which organizational unit are a given computer list in my domain

find out in which organizational unit are a given computer list in my domain

Content Index :

find out in which organizational unit are a given computer list in my domain
Tag : powershell , By : Dominique Vocat
Date : December 01 2020, 05:00 PM

Does that help I have a list of hundreds od computers selected from my domain. I would like to make a report that shows up in which OU are all of them. I found out that this cmdlet can perform the task I need: , Here is an example :
#load a list of computers
$computerList = Get-Content "computerList.txt"

#results array
$results = @()

#for each computer
foreach($computerName in $computerList) {
    #add result of command to results array
    $results += Get-ADComputer $computerName -Properties Name, DistinguishedName | Select Name, DistinguishedName

#send results to CSV file
$results | Export-Csv "computerOUs.txt" -NoTypeInformation

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Getting the parent organization unit (if any) of an organizational unit in Active Directory

Tag : chash , By : kennystone
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , First : From the pure Directory point of vue, you've got in your organizationalUnit (OU) an attribute called "distinguishedName" which looks like :
String myADSPath = "LDAP://onecity/CN=user,CN=Users,DC=onecity,DC=corp,DC=fabrikam,DC=com";
DirectoryEntry myDirectoryEntry=new DirectoryEntry(myADSPath, UserName, SecurelyStoredPassword);

Console.WriteLine("Parent is :"+myDirectoryEntry.Parent.Path);

Get OU (Organizational Unit) name that a local computer belongs to using C++

Tag : cpp , By : Comfly
Date : March 29 2020, 07:55 AM
Hope that helps For a simple WINAPI (not COM) way to acces Active Directory in C or C++ see Lightweight Directory Access Protocol
void AfficheErreurLdap(char *fonction, ULONG rc);

*       Fonction d'entrée du programme 

void main(int argc, char* argv[])
  LDAP *pSessionLdap;    // Pointeur vers la session LDAP
  char *pHote;           // Pointeur vers la chaîne représentant le nom de l'hôte   
  char *pUtilisateur;    // Pointeur vers la chaîne représentant l'utilisateur  
  char *pMotDePasse;     // Pointeur vers la chaîne représentant le mot de passe
  char *pRacineLdap;     // Pointeur vers la racine Ldap
  ULONG rc;                // Récupération du code de retour des appels
  LDAPMessage   *pResultat; // Pointeur vers le message résultat de la réquête LDAP
  LDAPMessage   *pEntree;     // Utilisée lors du parcours du résultat pour l'affichage

  char *pDN;                 // Pointeur vers le DN d'une entrée du résultat
  char *pAttribut;     // Pointeur vers la chaîne représentant l'attribut
  BerElement *pBer = NULL;// "curseur" interne à l'API LDAP pour le parcours des elts 
  char **pValeurs;            // Valeurs de l'attribut lors de l'affichage du résultat
  int    i;                             // Indice pour la parcours des valeurs  d'attribut

  /* Analyse des Paramètres de lancement et affichage d’un message d’erreur si incorrect */
  if (argc != 5)
    fprintf(stderr,"Syntaxe :\n\tex_cldap_1 Hote Utilisateur MotDePasse RacineLdap\n");
    exit (1);
  /* Récupération des paramètres des lancement  */
  pHote = argv[1];
  pUtilisateur = argv[2];
  pMotDePasse = argv[3];
  pRacineLdap = argv[4];

  /* Ouverture de la session LDAP et récupération du handle de session */
  pSessionLdap = ldap_open( pHote, 389);    /* 389 est le numéro de port standard LDAP */

  if ( pSessionLdap == NULL ) 
    // En cas d'erreur : affichage du message d'erreur adéquat 
    perror( "ldap_open" );
    exit( 2 );

  printf("Ouverture de la session réalisée\n");

  /* Authentification du client                                                                                                             */
  /* Pour l'exemple, l'authentification est faite en tant qu'anonyme    */
  rc = ldap_simple_bind_s(pSessionLdap, pUtilisateur, pMotDePasse);
  if ( rc != LDAP_SUCCESS ) 
    // Erreur lors de l'authentification, on termine après affichage d'un message
    AfficheErreurLdap("ldap_simple_bind_s", rc);

    exit( 3 );

  printf("Authentification réalisée\n");

  /*                                                                                                                                */
  /* Recherche des données dans l'annuaire                  */
  /*                                                                                                                                */
  rc = ldap_search_s(pSessionLdap,            // Session LDAP
    pRacineLdap,                    // Base de la recherche
    "(objectClass=*)",      // Filtre de recherche
    NULL,                               // Attributs que l'on souhaite visualiser
    0,                                      // Indique si l'on souhaite uniquement les types (1) ou 
    // Les attributs et les valeurs (0)
    &pResultat ) ;              // Pointeur vers le résultat

  if (rc != LDAP_SUCCESS ) 
    // Erreur lors de la recherche, on termine après affichage du message d'erreur
    AfficheErreurLdap("ldap_search_s", rc);
    exit (4);

  printf("Requête réalisée\n");

  /* On va maintenant parcourir le résultat et afficher les couples */
  /* attributs, valeurs                                                                                                                         */

  pEntree = ldap_first_entry( pSessionLdap, pResultat );

  while (pEntree != NULL)
    // Récupération du DN, et affichage de celui-ci
    pDN = ldap_get_dn( pSessionLdap, pEntree );
    if ( pDN != NULL ) 
      printf( "dn: %s\n", pDN );

      // Libération de la mémoire allouée par l'API LDAP
      ldap_memfree( pDN );  

    // Pour chaque attribut, on va lire le couple attribut, valeur 
    pAttribut = ldap_first_attribute( pSessionLdap, pEntree, &pBer );
    while (  pAttribut != NULL)
      // Récupération des valeurs associées à un attribut 
      pValeurs = ldap_get_values( pSessionLdap, pEntree, pAttribut);

      if (pValeurs  != NULL ) 
        for ( i = 0; pValeurs[i] != NULL; i++ ) 
          printf( "%s: %s\n", pAttribut, pValeurs[i]);

        // Libération des valeurs lues 
        ldap_value_free( pValeurs ); 

      // Libération de la mémoire utilisée par l'attribut 
      ldap_memfree( pAttribut );    

      // Lecture de l'attribut suivant
      pAttribut = ldap_next_attribute( pSessionLdap, pEntree, pBer );

    // Passage à la ligne dans l'affichage
    printf( "\n\n" );

    // Récupération de l'entrée suivante de l'annuaire
    pEntree = ldap_next_entry( pSessionLdap, pEntree );

  // Libération du message de résultat
  ldap_msgfree( pResultat );

  /* Fin de la session LDAP     */
  ldap_unbind( pSessionLdap );

* Fonction permettant d'afficher les erreurs des opérations LDAP 
void AfficheErreurLdap(char *fonction, ULONG rc)
  fprintf(stderr,"Erreur LDAP dans la fonction '%s', Code : %ld (0x%xld)\n", fonction, rc,rc);

How can I find what Organizational Units a computer is part of? ( Active Directory C# )

Tag : chash , By : user119605
Date : March 29 2020, 07:55 AM
seems to work fine Here's a solution using PrincipalContext and ComputerPrincipal in the System.DirectoryServices.AccountManagement namespace
string machineOU;
using (var context = new PrincipalContext(ContextType.Domain))
using (var comp = ComputerPrincipal.FindByIdentity(context, Environment.MachineName))
    machineOU = String.Join(",", comp.DistinguishedName.Split(',')
                                                       .SkipWhile(s => !s.StartsWith("OU="))

Query Active Directory/LDAP, find users in nested organizational unit

Tag : development , By : Ravenal
Date : March 29 2020, 07:55 AM
it should still fix some issue memberOf is looking for a group, not an OU. You should create a group to restrict access, add the appropiate users to the group, and specify the group's distinguished name in the filter. You should note that the simple 'memberOf={DN}' filter does not take into account nested group membership.
Edit: If you really want to restrict it to users in the OU, then you need to change the base DN of the search to the OU, and take out the memberOf parameter to the search.

Tag : windows , By : Steve
Date : March 29 2020, 07:55 AM
wish helps you You probably need to specify the full path.
Have you tried 'OU=Computers,OU=Testing,DC=GPO,DC=local' ?
Related Posts Related QUESTIONS :
  • Weird Coalesce Behavior
  • Search for a word within a file that has a specific modified date
  • How to fetch first column from given powershell array?
  • How to add text to a file foreach column using PowerShell?
  • How to share data between cmdlets in a module?
  • How to exclude some column in CSV using Powershell?
  • ARM Template for Redis Cache failing to deploy
  • Copy folders that match names to other sub folder of matching directory
  • How to set parameters for SaveAs() dialog in Word.Application?
  • Attempting to Filter out All .p12 AND .pfx files from a given Directory
  • Powershell FTP Script String Concatenation
  • How to GET variables used in a specific BUILD in Azure Devops / TFS via api
  • Cleaning up DistributionGroup in PowerShell
  • PowerShell method Contains not working as expected
  • Feeding Get-ChildItem path info from an array - Illegal characters
  • Script argument as private scope variable
  • PowerShell Hashtable to JSON without Quotes
  • How to set as variable csv column using powershell?
  • Move flag from one script to another in PowerShell
  • Sort-Object problem (one MAC address and two IP addresses)
  • concatenate columnar output in PowerShell
  • When a list of objects is retruned from Get-EventLog that itself contains an array of strings, how do I access the array
  • Passing down a variable to function creates an array
  • Get-Date cannot convert null to type "System.Datetime"
  • I want run PowerShell commands using administrator with normal PowerShell user
  • How to using loop to find a file and remove it using PowerShell?
  • PowerShell Get-ChildItem on folder that does not exist behaves different with the -recurse flag
  • How to do looping for checking an existing folder with PowerShell?
  • Having trouble outputting to a CSV file. I know the output is a curly brackets "collection", but I'm stumped
  • How to replace last part of a string dynamically?
  • Checking to see if PowerShell Command worked, Crap Error
  • (Date).ToString does not use specified delimiter
  • Loop through multiple array in powershell
  • How to mapping a file by matching data using powershell?
  • How to define the return type / OutputType of a function
  • Use multiple CSVs out a folder individually and save their names
  • Get-FileHash command in powershell 2.0
  • How to pick a files based on the first received in PowerShell?
  • Is there a way to get a range for numbers larger than int32?
  • PowerShell and process exit codes
  • Parse a txt file or an input using PowerShell
  • Store different positional numbers on a variable
  • Windows Server 2012 R2 Remote Desktop access problems
  • Output filename weirdly
  • Filtering with wildcards
  • Internet Explorer object doesn't have Document child
  • Accept where clause in an advanced function
  • Howto get an INT output from select statement
  • After Stop-Process, task still shows on Get-Process
  • Get-ADUser using old pre-Windows 2000 Logon name instead of CN
  • Nonexistent LiteralPath Property of System.IO.FileInfo Object Bound to Parameter
  • How to Read the CSV file which has two data set (I.e Two Different Header and Column)
  • PS Script to print directory names if file type in it
  • Unable to delete files from the list using Remove-Item in PowerShell
  • Get results of For-Each arrays and display in a table with column headers one line per results
  • Running a powershell command using full path and arguments from command line
  • In Powershell, How do I get the Values out of an array returned by an object?
  • Checking if windows security patches are installed on multiple servers
  • how to set EnabledProtocols with IISAdministration module
  • Comparing LastWriteTime and CreationTime
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com