ImportPSModule Failure Detection

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

I am interested to know if the module could not be imported for any reason (for example, the file was not found, etc.). Including such code in the try block does not throw an exception in the event of a failure, and the function seems to fail and continues to work if it cannot import the module.

Is there a way to get a warning in the code if the import fails?

I am trying to do something like the following. The module "TestModule1234" does not exist in the code below. The catch block does not throw an exception.

Note. This is just a prototype test code, so please ignore errors related to the production code.

 try { //Initializing the PowerShell runspace InitialSessionState psSessionInitialState = InitialSessionState.CreateDefault(); LogFile.Log("Importing Module TestModule1234"); psSessionInitialState.ImportPSModule(new[] { "TestModule1234" }); LogFile.Log("Creating Powershell Runspace"); m_PoshRunspace = RunspaceFactory.CreateRunspace(psSessionInitialState); } catch (System.Exception ex) { LogFile.Log("Failed to create a Powershell Runspace"); LogFile.Log(ex.ToString()); throw; } 
+2
source share
1 answer

For some reason, missing modules are not considered fatal errors. But they are still transcoded errors. To solve the problem, do:

  • Open your workspace to Open() . Do it in the try block to catch other exceptions, they are possible, I had such cases in practice.
  • Get the standard error list ( $Error ) and analyze it after opening the “missing modules” or other errors for certain errors.

Here is a working example in PowerShell using only .NET methods, so it literally translates to C #. This script is not interrupted (exceptions are not thrown), but it shows an error received as an Error variable:

 $psSessionInitialState = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault(); "Importing Module TestModule1234" $psSessionInitialState.ImportPSModule(@("TestModule1234")) "Creating PowerShell Runspace" $PoshRunspace = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($psSessionInitialState) "Opening PowerShell Runspace" $PoshRunspace.Open() "Getting Runspace Error" $PoshRunspace.SessionStateProxy.PSVariable.GetValue('Error') 

Output

Importing a TestModule1234 module Creating a Runspace Powershell opening Runspace Powershell Getting a Runspace error script Error-Module: The specified module "TestModule1234" was not loaded because an invalid module file was found in any module directory. + CategoryInfo: ResourceUnavailable: (TestModule1234: String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId: Modules_ModuleNotFound, Microsoft.PowerShell.Commands.ImportModuleCommand

+3
source

All Articles