I'm trying to convert my PowerShell function to use DirectorySearcher with the relevant filter, properties, etc. to find stale computers because Microsoft's Search-ADAccount is insufficient for what I need, and so I don't want my new function to rely on any underlying modules, i.e. get-adcomputer, because I heard it's best practice to rely as little as possible on external functions.
Here's the code I have thus far which seems to get me most of the way there, but I'm having trouble formatting the data into human-readable results that get-adcomputer does so nicely.
$FileTimeUTC = (get-date).adddays(-90).ToFileTimeUtc()
$Credential = get-credential
$Searcher = new-object -typename system.directoryservices.directorysearcher
$Searcher.Filter = "(&(objectclass=computer)(operatingsystem=windows*)(!(primarygroupid=516))(!(operatingsystem=*server*))(lastlogontimestamp<=$filetimeutc))"
$Searcher.PropertiesToLoad.Add('Name')
$Searcher.PropertiesToLoad.Add('Description')
$Searcher.PropertiesToLoad.Add('DistinguishedName')
$Searcher.PropertiesToLoad.Add('OperatingSystem')
$Searcher.PropertiesToLoad.Add('OperatingSystemServicePack')
$Searcher.PropertiesToLoad.Add('Created')
$Searcher.PropertiesToLoad.Add('PasswordLastSet')
$Searcher.PropertiesToLoad.Add('LastLogonDate')
$DomainDN=([adsisearcher]"").SearchRoot.Path
$domain = new-object -typename system.directoryservices.directoryentry -argumentlist $DomainDN, $Credential.UserName, $Credential.GetNetworkCredential().password
$searcher.searchroot = $domain
$objs = $searcher.findall()
return $objs
What I get is a mess with just Path and Properties, not in the format that I would normally get if I had instead used this:
get-adcomputer -filter * -properties Name,Description,DistinguishedName,OperatingSystem,OperatingSystemServicePack,Created,PasswordLastSet,LastLogonDate
Need help formatting the results in $objs if possible. Thank you in advance!
Try that Get-ADComputer with just one computer name and then pipe the result into Get-Member. Close to the top of the output you'll see the TypeName. PowerShell had done all the work of packaging up the data in an easy to use object.
Now have a look at one of entries in "$objs". They're hardly the same thing, are they?