ImportPSModule Failure Detection

Question:

I am trying to use InitialSessionState.ImportPSModule in order to import a Powershell module.

I am interested in knowing if importing of the module failed due to any reason (e.g file not found etc.). Putting such code in the try block does not raise an exception in the case of failure and the function seems to fail silently and continue if it is not able to import the module.

Is there a way to be alerted in the code if the import fails?

I am trying to do something like the following. In the code below, the module “TestModule1234” does not exist. The catch block does not catch an exception.

Note: This is just prototype test code, so please ignore any production code related irregularities.

Answer:

For some reasons missing modules are not treated as fatal errors. But they are
still recoded errors. In order to solve the problem do:

  1. Open your runspace by Open(). Do this still in the try block in order to catch other exceptions, they are possible, I had such cases in practice.
  2. Get the standard error list ($Error) and analyse it after opening for specific “missing module” errors or other errors.

Here is the working example in PowerShell using only .NET methods, so that it is literally translated to C#. This script does not fail (exceptions are not thrown) but it shows the error obtained as the variable
Error:

Output

Importing Module TestModule1234 Creating Powershell Runspace Opening
Powershell Runspace Getting Runspace Error Import-Module : The
specified module ‘TestModule1234’ was not loaded because no valid
module file was found in any module directory.
+ CategoryInfo : ResourceUnavailable: (TestModule1234:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

Source:

ImportPSModule Failure Detection by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply