Author Posts

July 20, 2018 at 9:33 pm

Hello,

I created this script to delete any non-desktop computers from AD that have not been logged into for at least 180 days. It queries an array of OU's for eligible computers. If one or more OU's in the array is removed from Active Directory, an error will occur and a notification email will be sent. Otherwise, it deletes the computers from AD.

The issue is the variable $($errormessage) in the message body is blank.

Message I get:
The Delete Stale computers script failed due to error ".
One of the OU's listed maybe missing in Active Directory.
Please review the list of OU's and check if they are still present in Active Directory

Message I want:
The Delete Stale computers script failed due to error 'directory object not found'.
One of the OU's listed maybe missing in Active Directory.
Please review the list of OU's and check if they are still present in Active Directory

If I run the script again in the current session, it works. Apparently the variable is still null until the script completes. How do I fix it to work on the first run?
Thanks!

   
Import-Module ActiveDirectory 

$Smtpserver = "smtpmail.domain.com"
$From = "noreply@domain.com"
$To = "user@domain.com"
$Subject = "Delete Stale Computers Failed"
$Body = "The Delete Stale computers script failed due to error '$($errormessage)'.   One of the OU's listed maybe missing in Active Directory.  Please review the list of OU's and check if they are still present in Active Directory" 

$date = [DateTime]::Today.AddDays(-180)

$ous = @(
       'OU=Name,DC=domain,DC=com';
       'OU=Laptop,OU=Computers,OU=City,OU=Production,DC=domain,DC=com';
       'OU=Windows 8,OU=Workstations,DC=domain,DC=com';
       'OU=Windows 8 Prod,OU=Workstations,DC=domain,DC=com';
       'OU=Linux,OU=Workstations,DC=domain,DC=com';
       'OU=Windows 8,OU=Workstations,DC=domain,DC=com';
       )


    try {
        $results = $ous | 
        ForEach-Object { Get-AdComputer -Properties LastLogonDate -Filter {LastLogonDate -le $date} -Searchbase $_ } | 
        Where-Object {$_.SamAccountName -cnotmatch "D-"} 
    }

    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException] {          
    }

    finally {
        
        if ($error[0].exception.message.Contains("Directory object not found")) {
            $errormessage = $error[0].exception.message.ToLower()
            Send-MailMessage -SmtpServer $Smtpserver -From $From -To $To -Subject $Subject -BodyAsHtml $Body
            $error.Clear()                   
        }

            else {
                $results | Remove-ADComputer -Confirm:$false          
            }
    }
 

July 20, 2018 at 10:01 pm

So, the problem is that the expression is evaluated on line 8, at which point I would expect $errormessage to in fact be empty.

You need to move line 8 underneath line 34.

July 21, 2018 at 2:43 am

Thanks for your help Don. That did it.