Reputation: 1
Import-Module ActiveDirectory
Get-ADComputer -Filter {enabled -eq $true} -properties *|select Name,
| Out-File -FilePath c:\Powershell.txt
I am trying to export a list to txt file and have it display a list of all the computers on my domain by name and the OU or group it is assigned to. i am able to retrieve the name with this, but would like to ad a OU Colum.
Upvotes: 0
Views: 2139
Reputation: 60025
This what I do, it is a bit slower than the other examples provided but it will prevent any timeout on the Get-ADcomputer
cmdlet. I'm also using CanonicalName
to have an absolute path of the OU because OUs can have the same name and Canonical is easier to read than Distinguished.
$OUs = Get-ADOrganizationalUnit -Filter * -Properties CanonicalName
$Result = foreach($OU in $OUs)
{
$hash = @{
Filter = 'Enabled -eq $true'
SearchScope = 'OneLevel'
SearchBase = $OU.DistinguishedName
}
foreach($computer in Get-ADComputer @hash)
{
[pscustomobject]@{
ComputerName = $computer.Name
OU = $OU.CanonicalName
}
}
}
Upvotes: 0
Reputation: 25001
Honestly, I would derive the OU from the DistinguishedName
value. It will be quicker than running additional ActiveDirectory module PowerShell commands. You can then output the OU value using Select-Object's calculated properties. I would also recommend outputting to CSV (using Export-Csv) since that format is easily readable by PowerShell and other file editing tools.
Get-ADComputer -Filter 'Enabled -eq $true' |
Select-Object Name,@{n='OU';e={$_.DistinguishedName -creplace '^.*?,(?=[A-Z]{2}=.*)'}} |
Export-Csv -Path c:\Computers.csv
Note that the CSV export will have a header row and values will be delimited by comma. If you prefer a different delimiter, you can use the -Delimiter
parameter or your PowerShell session's default list separator with the -UseCulture
switch.
-creplace
is a case-sensitive version of -replace
operator.
^.*?,(?=[A-Z]{2}=.*)
is regex syntax for matching the text to replace. ^
denotes the start of the string. .*?,
matches a few characters as possible until a ,
is matched. But since a CN
value can contain ,
characters, we only want to stop matching when it precedes OU=
or DC=
. This is why we have positive lookahead (?=[A-Z]{2}=.*)
. [A-Z]{2}
matches exactly two capital letters followed by =
.
Upvotes: 1
Reputation: 174485
Since the DistinguishedName
value contains the OU RDN, we can extract it with a bit of string splitting magic:
Get-ADUser -Filter * |Select Name,@{Name='OU';Expression={$_.DistinguishedName -split '(?<!\\),' |Select -Index 1}}
This will give us only the RDN (ie. OU=Company Users
), if you want the full DN of the OU, do:
Get-ADUser -Filter * |Select Name,@{Name='OU';Expression={$_.DistinguishedName -split '(?<!\\),',2 |Select -Skip 1}}
The pattern (?<!\\),
will match any ,
in the DN only if not preceded by \
- this is to avoid splitting on escaped ,
's, like in CN=LastName\, FirstName,OU=Users,...
Upvotes: 2