我正在尝试使用InitialSessionState.ImportPSModule以导入Powershell模块。
我有兴趣知道是否由于任何原因(例如找不到文件等)而导致模块导入失败。在失败的情况下,将此类代码放在try块中不会引发异常,并且该函数似乎会以静默方式失败,如果无法导入模块,则该函数会继续执行。
如果导入失败,是否有办法在代码中发出警报?
我正在尝试执行以下操作。在下面的代码中,模块“ TestModule1234”不存在。catch块不捕获异常。
注意:这只是原型测试代码,因此请忽略与生产代码相关的任何违规行为。
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;
}
Run Code Online (Sandbox Code Playgroud)