Background: We have setup an Active Directory OU called Quarantine to temporarily store user accounts that have just been terminated before terminating their office 365 mailboxes licenses, legal holds and archives. My director wants me to search that OU for all users with data in a CustomAttribute field (text format) that we are populating with a termination date (looks like a date but the default format of the field is text). Once I get all users who have info in that field, I have to convert it to date format and then for those users who are terminated 90 days ago or more I have to process a script to disable legal hold. For those users who are 89 days or less I do NOT disable the legal hold.
This has proven more difficult than I thought. I'm not sure I'm converting the text field properly and I'm also not sure how to differentiate between the two filters. I have one example of a script below that tries to convert the date (unsuccessfully) but it does not try two different filters because I'm not sure how to set those up (I know how to get 90days plus...I think...but I can't figure out how to get results for those that are 89 days or less):
Script 1
$RelayMailServer = "relay.domain.com" $FromAddress = "noreply@domain.com" $password = ConvertTo-SecureString "password" -AsPlainText -Force $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList adminacct@domain.com,$password $s = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $cred -Authentication Basic -AllowRedirection $importresults = Import-PSSession $s $adusers = get-aduser -filter * -searchbase 'ou=quarantine,dc=domain,dc=com' | select userprincipalname $results = @() $ErrorActionPreference = "continue" foreach ($user in $adusers) { $results += get-mailbox $user.userprincipalname -resultsize unlimited | ?{$_.customattribute7 -ne ""} |` select UserPrincipalName,CustomAttribute7 } If ($results) { function Convert-DateString ([CustomAttribute7]$Date, [CustomAttribute7[]]$Format) { $dateresult = New-Object DateTime $convertible = [DateTime]::TryParseExact( $Date, $Format, [System.Globalization.CultureInfo]::InvariantCulture, [System.Globalization.DateTimeStyles]::None, [ref]$dateresult) if ($convertible) { $dateresult } } } If (!$results) { Write-Host "variable is null" } If ($results){$file = "c:\Office365\TermedUsersCA7.csv"} If ($results){$results | Export-csv $file -NoTypeInformation} If ($results) {import-csv c:\Office365\TermedUsersCA7.csv} Foreach ($result in $results) { $qdate += $result.customattribute7 -gt (get-date).AddDays(-90) #$qdate1 = get-date customattribute7.adddays(+90) #$qdate2= echo date{'yyyy-mm-dd', $qdate1. ' + 90 days'} Get-Mailbox -identity $_.userprincipalname -filter {CustomAttribute7 -gt $qdate}| ` select userprincipalname, customattribute7 | export-csv "C:\office365\q90users.csv" } Remove-PSSession $s