gpt4 book ai didi

c# - ImportPS 模块故障检测

转载 作者:太空狗 更新时间:2023-10-30 01:06:54 24 4
gpt4 key购买 nike

我正在尝试使用 InitialSessionState.ImportPSModule 来导入 Powershell 模块。

我很想知道模块导入是否由于任何原因(例如找不到文件等)而失败。将此类代码放在 try block 中不会在失败的情况下引发异常,并且函数似乎会静默失败并在无法导入模块时继续。

如果导入失败,有没有办法在代码中提醒?

我正在尝试执行以下操作。在下面的代码中,模块“TestModule1234”不存在。 catch block 不捕获异常。

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

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

最佳答案

由于某些原因,丢失的模块不会被视为 fatal error 。但他们是仍然重新编码错误。为了解决问题,请执行以下操作:

  1. 通过Open() 打开你的运行空间。仍然在 try block 中执行此操作以捕获其他异常,它们是可能的,我在实践中遇到过这样的情况。
  2. 获取标准错误列表 ($Error) 并在打开后分析它是否存在特定的“缺少模块”错误或其他错误。

这是仅使用 .NET 方法的 PowerShell 中的工作示例,因此它直接翻译为 C#。这个脚本不会失败(不会抛出异常)但它显示了作为变量获得的错误错误:

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

输出

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

关于c# - ImportPS 模块故障检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13929292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com