See if this is close to your requirements:
$WHATIF = $true
$currentday = (Get-Date).ToUniversalTime().Date
$validedate = (Get-Date).adddays(7).ToUniversalTime().Date
Get-ADComputer -ldapfilter '(managedby=*)' -properties name, managedby, extensionAttribute15 |
ForEach-Object{
$ExpiryDate = $_ | Select-Object -expand extensionAttribute15
$dn = $_.distinguishedname # needed in "Catch" block
if(-not $ExpiryDate){
Write-Host "Null not allowed. Correcting to within 7 days. Maximum accepted value." -ForegroundColor DarkRed
Set-ADcomputer -Identity $_.distinguishedName -Clear "extensionAttribute15" -WhatIf:$WHATIF
Set-ADcomputer -Identity $_.distinguishedName -Add @{extensionAttribute15 = $validedate.ToString("MM/dd/yyyy")} -WhatIf:$WHATIF
}
else {
Try{
$ExpiryDate = [datetime]$ExpiryDate
if ($ExpiryDate -gt $validedate){
Write-Host "Date is more than 7 days. Correcting to within 7 days. Maximum accepted value." -ForegroundColor Red
Set-ADcomputer -Identity $_.distinguishedName -Clear "extensionAttribute15" -WhatIf:$WHATIF
Set-ADcomputer -Identity $_.distinguishedName -Add @{extensionAttribute15 = $validedate.Date.ToString("MM/dd/yyyy")} -WhatIf:$WHATIF
}
elseif($ExpiryDate -le $currentday ) {
write-host "Emptying Managed by field for $($_.name)" -ForegroundColor Yellow
#some code
}
else{
write-host "Date is inferior to 7 days we don't take action for $($_.name)" -ForegroundColor Green
}
}
Catch{
Write-Host "Invalid expiry date found in extentionAttribute15. Correcting to +7 days from today."
Set-ADcomputer -Identity $dn -Clear "extensionAttribute15" -WhatIf:$WHATIF
Set-ADcomputer -Identity $dn -Add @{extensionAttribute15 = $validedate.ToString("MM/dd/yyyy")} -WhatIf:$WHATIF
}
}
} #end foreach