ImportPSModule Failure Detection

2019-02-25 03:04发布

问题:

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.

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;
}

回答1:

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:

$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 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