ImportPSModule Failure Detection

℡╲_俬逩灬. 提交于 2019-12-01 20:51:43
Roman Kuzmin

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!