How can I find computers with LastLogonTimestamp less than a certain date OR null

305 Views Asked by At

The following code returns all the computerprincipals that have logon date prior to 3 months ago but does not get those with null for a lastlogontimestamp

PrincipalContext context = new PrincipalContext(ContextType.Domain);
PrincipalSearchResult<ComputerPrincipal> computers = ComputerPrincipal.FindByLogonTime(context, DateTime.Now.AddMonths(-3), MatchType.LessThanOrEquals);

How can I elegantly also add to "computers" those that have null valued "lastlogontimestamp" values?

1

There are 1 best solutions below

2
On BEST ANSWER

I did away with the ComputerPrincipal.FindByLogonTime, since it can't find null LogonTime and went with the old classic, the DirectorySearcher

DirectorySearcher Computersearcher = new DirectorySearcher
{
    SearchRoot = new DirectoryEntry(baseOU),
    Filter = "(&(whenCreated<=" + WhenCreated + ")(!(userAccountControl=2))(|(lastLogonTimestamp<=" + DateInt + ")(lastLogonTimestamp=0))(objectClass=computer))",
    SearchScope = SearchScope.Subtree,
    PageSize = 1000,
    Sort = new SortOption("Name", SortDirection.Ascending)
        };
    SearchResultCollection ComputerResults = Computersearcher.FindAll();
}

This has the unfortunate side effect that the observable collection that I used to create, no longer displays the Name in my WPF Listbox (despite setting DisplayNamePath).

A whole new issue, but the current one is "solved"