First, I have no formal training in Powershell, so most of what I write is adapted code or is relatively simple. I'm having problems retrieving either extended properties for a machine, or reorganizing the list of columns that is returned.
In my organization, a PC can be either a member of a the local OU that I'm privy to, or an enterprise OU that I have no rights to. A scan of my local OU Groups wouldn't give me all the results I'm looking for. I was able to find the answer to apply this logic to Users and Group memberships, but can't seem to get it working for PCs.
Import-Module ActiveDirectory
$OU = "OU=Computers,OU={ORG UNIT}"
$Path = "C:\{FILE LOC}\AD-groupPClist_$(get-date -f yyyyMMdd_HHmm).csv"
$PC = ForEach ($P in (Get-ADComputer -Filter * -SearchBase $OU))
{
$Machine = Get-ADComputer $P -Properties MemberOf
$Groups = ForEach ($Group in ($Machine.MemberOf))
{
(Get-ADGroup $Group).Name
}
$Groups = $Groups | Sort
ForEach ($Group in $Groups)
{
New-Object PSObject -Property @{
Group = $Group
PCName= $Machine.Name
}
}
}
$PC | Export-CSV $Path -NoTypeInformation
When I try to add the DNSHostName column (for example), it appears as the first column in the results, even if it's listed third. In this case, if I added DNSHostName, I'd want the output file to be Group Name, PCName, DNSHostName (or some other attribute); but in that order.