First time posting so bear with me... 😀
I've been given a task to take a list of user accounts (roughly 80,000) and export all groups they are a member of, including nested groups, but only those with a mail address. So the problem I'm running into is the fact that this script takes an extremely long time to finish. I've tried to eliminate any extra script, but still... 10+ hours to run. Also, when I execute the script in PSv3 or v4 the powershell process eats multiple GB of ram after it's been running a while. So I've resorted to using a custom export-csv function that can append, since I seem to only be able to use PSv2.
Good God, a nice challenge :-). If I understand you correctly, you have two issues. Speed and memory consumption when the script runs. Ideally you would like a script that runs fast without consuming much memory, like Winnie the Pooh, Both please. Reducing on of them might have impact on the other.
1. If you have trust enabled to other AD forests, you might want to look into adding the KeepForeignSecurityPrincipals parameter-switch for the get-qadmemberof cmdlet.
2. Next I would investigate the performance impact on applying the UseDefaultExcludedProperties parameter in combination with the IncludedProperties parameter since you only require the sAMAccountname, dn, email attributes in your export
3. Experimental: Split the script up in more pieces and use import-clixml and export-clixml to "cache" data locally