如何从 C# 执行 Service Fabric Powershell 命令?

How to Execute Service Fabric Powershell commands from c#?

我使用 "System.Management.Automation.dll" 从 C# 代码执行 PowerShell 命令。但是我无法执行 Service Fabric 命令。

当我执行 Service Fabric 命令时,出现以下错误

The specified module 'ServiceFabric' was not loaded because no valid module file was found in any module directory

The term 'Connect-ServiceFabricCluster' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

我使用的代码是

 var shell = PowerShell.Create();
 shell.Commands.AddScript("Import-Module ServiceFabric");
 shell.Commands.AddScript("Connect-ServiceFabricCluster");
 var result = shell.Invoke();

当我直接从 PowerShell 命令 window 执行这些命令时,它们成功运行。

以上代码适用于其他 PowerShell 命令

我也试过使用物理路径加载模块 "C:\Windows\System32\WindowsPowerShell\v1.0\Modules\ServiceFabric" 那也没用。

为什么要尝试从 C# 调用 powershell 命令?所有 powershell 命令都与 API 相同 - 这意味着,对于每个命令,都有一个 API 可以直接使用。只需创建一个 FabricClient 并调用您需要的任何方法。