0

I've been working on a script to remove mobile devices from Exchange Online. Everything else works fine except this one bit:

foreach ($item in $userdevices) {
  Remove-MobileDevice -Identity $item -whatif
  [System.Runtime.Interopservices.Marshal]::ReleaseComObject($item) | Out-Null 
}

This line [System.Runtime.Interopservices.Marshal]::ReleaseComObject($item) | Out-Null is required for the script not to hang, but it outputs the error due to incompatibility with Mac.

The error I receive is:

MethodInvocationException: /Users/XXX/XXX/MDM.ps1:80:17
Line |
  80 |  …             [System.Runtime.Interopservices.Marshal]::ReleaseComObjec …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Exception calling "ReleaseComObject" with "1" argument(s): "COM Interop is not supported on this platform."

I have tried adding in try-catch mechanisms, -ErrorAction SilentlyContinue, -WarningAction SilentlyContinue, and a few other variations with no luck. I get this error:

ParserError: /Users/XXX/XXX/MDM.ps1:80:83
Line |
  80 |  … nteropservices.Marshal]::ReleaseComObject($item) -ErrorAction:Silentl …
     |                                                     ~~~~~~~~~~~~
     | Unexpected token '-ErrorAction' in expression or statement.

1 Answers1

0

[System.Runtime.InteropServices.Marshal]::ReleaseComObject($item) is an expression (a .NET method call), and in order to silence an exception (aka statement-terminating error) it may throw, you need try { ... } catch { ... }:

# Using just {} as the catch block means that any exception is *quietly ignored*.
try { 
  $null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($item) 
} catch {}

Note: $null = ... is a typically better-performing alternative to ... | Out-Null - see this answer for details.

Note:

  • If needed, the exception object is available via the automatic $_ variable inside the catch block; you an re-throw the exception simply with throw (no argument needed).

  • Even if you simply ignore the exception, it is still recorded in PowerShell's session-wide error log, the automatic $Error variable.


As for what you tried:

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($item) -ErrorAction SilentlyContinue  

This causes a syntax error, because the common -ErrorAction parameter (like all common parameters, i.e. -WarningAction too) only apply to commands, more specifically, to cmdlets (e.g., Get-ChildItem) and advanced functions and scripts (which behave like cmdlets, but, unlike the former, which are implemented via compiled code (.NET assemblies), are written in PowerShell).

Note that expressions and commands are each parsed according to separate syntax rules aka parsing modes, discussed in the conceptual about_Parsing help topic.

mklement0
  • 382,024
  • 64
  • 607
  • 775