powershellactive-directory

Powershell: Retrieving LogonDate in Active Directory


I've a list of computers, I'm checking if they are connected, if they aren't check with AD and "spit out" the one that aren't connecting for more than 3 months.

If it's connected then check if a services is installed.

Here's my code:

    Import-Module ActiveDirectory
$datecutoff = (Get-Date).AddDays(-90)
Get-Content "C:\powershell\pc.txt" | 
    foreach {
        if (-not (Test-Connection -comp $_ -quiet)){
            Write-host "$_ is down" -ForegroundColor Red
            $LastLog = Get-ADComputer -Identity $_ | Select LastLogonDate
            if($LastLog -lt $datecutoff){
                Write-host "$_ is offline for more than 3 months" -ForegroundColor Yellow  
            }
        } Else {
            $service = get-service -name masvc -ComputerName $_ -ErrorAction SilentlyContinue

            if ($service ){ 
                write-host "$_  Installed"
            } else {
                Write-host "$_  Not Installed"
            }
        }
    }

When it finds a disconnected computer it gives me the following error:

    Cannot compare "@{LastLogonDate=}" to "2020.04.16 18:49:19" because the objects are not the same type or the object "@{LastLogonDate=}" does not implement "IComparable".
At line:10 char:20
+                 if($LastLog -lt $datecutoff){
+                    ~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], ExtendedTypeSystemException
    + FullyQualifiedErrorId : PSObjectCompareTo

I know the error happens because my variable is saving wrong info, but I cannot find a way to only select the date in the AD.

Is there anyway to do this?


Solution

  • You have a couple of issues. You'll need to request that LastLogonDate is returned with Get-ADComputer as its not by default. You'll need to use the dotted notation method of selecting property LastLogonDate from the $LastLog object so your compare works.

    Import-Module ActiveDirectory
    $datecutoff = (Get-Date).AddDays(-90)
    Get-Content "C:\powershell\pc.txt" |
    foreach {
        if (-not (Test-Connection -comp $_ -Quiet)) {
            Write-Host "$_ is down" -ForegroundColor Red
            $LastLog = Get-ADComputer -Identity $_ -Properties LastLogonDate
            if ($LastLog.LastLogonDate -lt $datecutoff) {
                Write-Host "$_ is offline for more than 3 months" -ForegroundColor Yellow
            }
        } Else {
            $service = Get-Service -Name masvc -ComputerName $_ -ErrorAction SilentlyContinue
    
            if ($service ) {
                Write-Host "$_  Installed"
            } else {
                Write-Host "$_  Not Installed"
            }
        }
    }
    

    Side note. You can filter for aged computers like this Get-ADComputer -Filter 'LastLogonDate -lt $datecutoff'