Search code examples
powershellactive-directorytimeout

Search-ADAccount - This operation returned because the timeout period expired


I have the following code:

Search-ADAccount -AccountExpiring -TimeSpan "90" -ResultPageSize:100 -ErrorAction SilentlyContinue |
    where {$_.samaccountname.StartsWith("X") -or $_.samaccountname.StartsWith("Y")} |
    Select-Object samaccountname,Name,AccountExpirationDate |
    Export-Csv $PSScriptRoot\Results\AD_Expiration_Dates_Accounts_Next_90_days_$((Get-Date).ToString('dd_MM_yyyy')).csv -NoTypeInformation -Append

I keep getting the error mentioned in the title with or without the -ResultPageSize: option.

The interesting thing is that when I change the -TimeSpan value I get more or less values and the data seems therefore to be coherent but, it always ends with the same error nevertheless.

The thing is, I'm not sure I can trust these values; even when I remove the option -ErrorAction SilentlyContinue I don't get any other error or information.

Does anyone have any input on this?


Solution

  • In this instance, it'd be way better to use Get-ADUser with a proper filter for all the criteria you want, rather than returning a whole lot of results and then using a where clause on them.

    Also consider using the -searchbase option to limit which OU you search (if all the target accounts are in a specific OU).

    $now = get-date
    $90days = (get-date).adddays(90)
    get-aduser -filter '(AccountExpirationDate -gt $now) -and (AccountExpirationDate -le $90days) -and (samAccountName -like "X*" -or sAMAccountName -like "Y*" )' -properties AccountExpirationDate 
    | Select-Object samaccountname,Name,AccountExpirationDate