I’m writing some long-lived Exchange PowerShell connections for Exchange 2013 and Exchange Online for a customer doing a large migration. We have a problem with a flaky network that will randomly cause the remote PowerShell sessions to drop, and these always cause my scripts to run haywire and need to be restarted – either because we start getting assorted error messages for several minutes before the session itself drops, or because the session does finally drop, the next cmdlet in the script attempts to re-establish the implicit session and hangs on requesting credentials. And because it’s a multi-domain forest, if it’s the on-premises Exchange session that drops, we start getting failures because the re-established session loses the Set-ADServerSettings -ViewEntireForest value and defaults back to the local domain.
These scripts are meant to be run in long-lasting sessions on a central management server. I’ve stored the credentials in global variables (so they can be reused between scripts – the operators must provide them when they open PowerShell up and kick the scripts off) and have figured out how the scripts can detect if there’s a currently open session they can use (to avoid the overhead of setting up/tearing down the connection). However, I cannot figure out how to:
- Detect when there’s an error with the session
- Re-establish the session using the stored credentials instead of popping up a request for new ones
- Re-run Set-ADServerSettings as soon as the session is re-established
Does anyone have any pointers to resources that can help me figure out how to accomplish these tasks?
Thanks in advance.