how to Extract multiple OU name using Powershell's Get-ADOrganizationUnit & Get-ADComputer
In AD hostnames are created under location OU, inside location OU under computer sub OU. i need a script to extract both OU in excel. i am able to extract one OU details through below scrpit
Get-ADComputer -filter * -Properties ipv4Address, OperatingSystem,DistinguishedName |
select-object Name, ipv4Address, OperatingSystem,
@{label='OU';expression={$_.DistinguishedName.Split(',')[1].Split('=')[1]}}
i need help to extract main OU details please help
Solution 1:
If you want all OUs in the path, you can use a regex pattern to extract them.
[regex]$pattern = '(?<=OU=)(.+?)(?=,\w{2}=)'
$searchbase = 'OU=Company,DC=Domain,DC=LOCAL'
$properties = 'Name',
'ipv4Address',
'OperatingSystem',
@{n='OU';e={$pattern.Matches($_.DistinguishedName).Value -join ', '}}
$adparams = @{
Filter = '*'
Searchbase = $searchbase
Properties = 'ipv4Address',
'OperatingSystem'
}
Get-ADComputer @adparams |
Select-Object $properties
If you're after just the OU above computers, then something like this may work.
[regex]$pattern = '(?<=OU=)(.+?)(?=,\w{2}=)'
$searchbase = 'OU=Company,DC=Domain,DC=LOCAL'
$properties = 'Name',
'ipv4Address',
'OperatingSystem',
@{n='OUs';e={$pattern.Matches($_.DistinguishedName)[1].Value}}
$adparams = @{
Filter = '*'
Searchbase = $searchbase
Properties = 'ipv4Address',
'OperatingSystem'
}
Get-ADComputer @adparams |
Select-Object $properties