powershellactive-directoryou

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


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:

PS C:\Users\digiacomo.a-rti> Get-ADComputer "FIDS156041" -Properties DistinguishedName

but instead of a single computer FIDS156041, I want to pass to it as a parameter, a (txt or csv) file containing my list of computers, and if possible, output the result in another file that contains two columns: computer names and their OU. Is it possible? How can I do it?

Thank you very much in advance for your help!


Solution

  • 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