In event viewer I see the error (shortened here):
Description: The process was terminated due to an unhandled exception.
Exception Info: System.AccessViolationException at CertStore.Win32Utils.CertEnumCertificatesInStore(IntPtr, IntPtr)
I know that you cannot catch an AccessViolationException on any .NET version since 4.0, and that this is by design. I can find no documentation on how to handle it in PowerShell
My question is how do I catch this exception and stop it from completely crashing my script? In C# and other languages I could use [HandleProcessCorruptedStateExceptions]
but I can't find any documentation on this class in PowerShell.
Thank you in advance!
I don't know how to catch the exception, but it looks like you're working with the cert store and that's causing the exception. My problem was that trying to enumerate through the cert store and then opening it was throwing the Access Violation exception. By adding the 'Read Only' flag, I was able to get around the violation error and use a normal try catch for any other errors.
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($computer, "LocalMachine")
#Read only flag that fixed it.
$store.Open("ReadOnly")
$certs = $store.Certificates
$store.Close();