1

I'm having trouble with Try-Catch in PowerShell.

Here is the code I'm trying to use (note that $Wksn is passed to this routine):

$BitLockerNameSpace = "root\cimv2\security\MicrosoftVolumeEncryption"
$BitLockerClass = "Win32_EncryptableVolume"
$Filter = "DriveLetter = 'C:'"

Try {
   $BitLocker = Get-WmiObject -namespace $BitLockerNameSpace -Class $BitLockerClass -Filter $Filter -ComputerName $Wksn
} Catch {
   $SimplifiedStatus = "Cannot connect"
}

When I test this against a computer where I know RPC isn't available or against a computer is not valid, it doesn't "catch" the error:

Get-WmiObject : The RPC server is unavailable. (Exception from
HRESULT: 0x800706BA) At C:\Temp\Untitled67.ps1:39 char:20
+ ... BitLocker = Get-WmiObject -namespace $BitLockerNameSpace -Class $BitL ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Get-WmiObject], COMException
    + FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

What am I missing?

mconwell
  • 23
  • 2
  • 3
    Try appending `-ErrorAction Stop` to the Get-WmiObject line – Theo Mar 26 '21 at 14:24
  • 2
    In short: `try` / `catch` only acts on _terminating_ errors, whereas it is far more typical for cmdlets to report _non-terminating_ errors. For the `catch` block to get invoked, non-terminating errors must be promoted to terminating ones by passing `-ErrorAction Stop` or by setting `$ErrorActionPreference = 'Stop'` beforehand. See the [linked answer](https://stackoverflow.com/a/59641995/45375) for more information – mklement0 Mar 26 '21 at 14:29

0 Answers0