Dev*_*v28 4 .net c# powershell pssnapin runspace
我正在尝试使用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)
由于某些原因,缺少的模块不会被视为致命错误。但是它们仍然是重新编码的错误。为了解决问题,请执行以下操作:
Open()
。为了捕获其他异常,仍然可以在try块中执行此操作,因为我有这种情况。$Error
),并在打开后分析特定的“缺失模块”错误或其他错误。这是PowerShell中仅使用.NET方法的工作示例,因此可以将其从字面上转换为C#。该脚本不会失败(不会引发异常),但是会显示作为变量获取的错误
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')
Run Code Online (Sandbox Code Playgroud)
输出量
导入模块TestModule1234创建Powershell运行空间打开Powershell Runspace获取运行空间错误Import-Module:未加载指定的模块'TestModule1234',因为在任何模块目录中均未找到有效的模块文件。+ CategoryInfo:ResourceUnavailable:(TestModule1234:String)[导入模块],FileNotFoundException + FullyQualifiedErrorId:Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
归档时间: |
|
查看次数: |
1824 次 |
最近记录: |