Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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...
share|improve this question

1 Answer 1

up vote 0 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.