简体   繁体   中英

How can I call the FailoverClusters PowerShell module when working from C#?

I'm trying to call a PowerShell script from C#, which is usually very straightforward, except that for some reason the commands in the FailoverClusters module can never be found when calling from C# (not in scope). Here's what I've discovered:

The commands are always found when using an interactive PowerShell session:

PS C:\> Get-Cluster -Name DummyCluster

Name
----
DummyCluster

The commands are never found when using a local PowerShell session from C#:

var ps = PowerShell.Create();
ps.AddCommand("Get-Cluster");
ps.AddParameter("Name", "DummyCluster");
var r = ps.Invoke();
//Exception: command not found

I've tried about 6-7 different ways to import the module, and none of them worked. Here is one of them, taken from this tutorial on the subject:

var ps = PowerShell.Create();
var ss = InitialSessionState.CreateDefault();
var modules = new string[1]{"FailoverClusters"};
ss.ImportPSModule(modules);
var rs = RunspaceFactory.CreateRunspace(ss);
rs.Open();
var iv = new RunspaceInvoke(rs);
var r = iv.Invoke("Get-Cluster -Name DummyCluster");
//Exception: command not found

Interestingly, the commands are found when using a remote PowerShell session. This is a plausible work-around for certain use cases.

var ci = new WSManConnectionInfo(); //localhost remote connection
var rs = RunspaceFactory.CreateRunspace(ci);
rs.Open();
var iv = new RunspaceInvoke(rs);
var r = iv.Invoke("Get-Cluster -Name DummyCluster");
//Exception: access is denied

The FailoverClusters module is not visible from C#:

var ps = PowerShell.Create();
ps.AddCommand("Get-Module");
ps.AddParameter("ListAvailable");
ps.AddArgument("FailoverClusters");
var results = ps.Invoke();
Console.WriteLine(results.Count.ToString()); //prints 0

It is, however, visible from an interactive PowerShell session:

PS C:\> Get-Module -ListAvailable FailoverClusters


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   2.0.0.0    FailoverClusters                    {Add-ClusterCheckpoint, Add-ClusterDisk, Add-ClusterFileSe...

The FailoverClusters module is only available in 64-bit PowerShell sessions. Make sure that the C# DLL you're building is a 64-bit DLL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM