powershellscriptingactive-directory

Using powershell, how can I extract the OU path for a computer currently in AD?


I've managed to isolate the Distinguished Name, but I want to get rid of the Common Name part and only have the OU path. The length of the computer name will change depending on the pc, so I want to be able to only keep everything listed after the first comma (if that makes sense). It should work regardless if the PC name is 8 characters or 12 characters. This is what I have so far.

$testingThis = Get-ADComputer -Identity "ComputerExample" -Properties DistinguishedName | Select-Object -ExpandProperty DistinguishedName

Write-Output $testingThis

This is the output:

CN=example,OU=example,OU=example,OU=example,DC=madeup,DC=madeup,DC=madeup,DC=madeup

Solution

  • If I understand you correctly, you want to get only the OU where the machine is located.

    You can do this:

    $dn = $testingThis -split ',', 2
    $dn = $dn[1]
    $dn
    

    or use an function to do that

        function Get-ComputerOU {
        param (
            [string]$ComputerName
        )
    
        # Get the Distinguished Name (DN) of the computer from Active Directory
        $Computer = Get-ADComputer -Identity $ComputerName -Properties DistinguishedName
    
        # Check if the computer was found
        if ($Computer -ne $null) {
            # Split the DN and return only the OU part
            $OUPath = ($Computer.DistinguishedName -split ',', 2)[1]
            return $OUPath
        } else {
            Write-Output "Computer not found."
        }
    }
    
    # Example usage
    Get-ComputerOU "Computername"