ImportPSModule故障检测

我试图使用InitialSessionState.ImportPSModule来导入Powershell模块。

我有兴趣知道模块的导入是否由于任何原因(例如找不到文件等)而失败。 将这些代码放在try块中不会在出现故障时引发exception,并且该函数似乎无声地失败并且如果无法导入模块则继续。

如果导入失败,有没有办法在代码中发出警报?

我正在尝试做类似以下的事情。 在下面的代码中,模块“TestModule1234”不存在。 catch块没有捕获exception。

注意:这只是原型测试代码,因此请忽略任何与生产代码相关的违规行为。

 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. 通过Open()打开您的运行空间。 为了捕获其他exception,仍然在try块中执行此操作,它们是可能的,我在实践中遇到过这样的情况。
  2. 获取标准错误列表( $Error )并在打开特定“缺失模块”错误或其他错误后对其进行分析。

以下是PowerShell中仅使用.NET方法的工作示例,因此它实际上已转换为C#。 此脚本不会失败(不会抛出exception)但它会显示作为变量获取的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') 

产量

导入模块TestModule1234创建Powershell Runspace打开Powershell Runspace获取Runspace错误导入模块:未加载指定的模块“TestModule1234”,因为在任何模块目录中都找不到有效的模块文件。 + CategoryInfo:ResourceUnavailable:(TestModule1234:String)[Import-Module],FileNotFoundException + FullyQualifiedErrorId:Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand