Reputation: 1160
I want to examine a MS service (with display name 'MyService', say) on a failover cluster and to this end I want to evaluate powershell commands in C#. The commands I have in mind are
$a = Get-ClusterResource "MyService"
$b = Get-ClusterGroup $a.OwnerGroup.Name | Get-ClusterResource | Where-Object {$_.ResourceType -eq "Network Name"}
I already figured out how to load the FailoverClusters module in to the power shell instance. I'm creating the shell using the following code:
InitialSessionState state = InitialSessionState.CreateDefault();
state.ImportPSModule(new[] { "FailoverClusters" });
PowerShell ps = PowerShell.Create(state);
With this ps
instance I can now successfully execute single cluster evaluation commands.
Now my understanding is that if I'm using ps.AddCommand
twice, first with Get-ClusterResource
and then with the commands from the next line, I will pipe the result of Get-ClusterResource
into the next command, which I don't want to do since the -Name
parameter of Get-ClusterResource
does not accept results from a pipe. (Rather the second line would be build using AddCommand
)
My question is, how do I pass the variable $a
to the second line in a c# powershell invoke? Do I have to create two power shell instances and evaluate the first line first, passing it's result somehow to a second call, or is it possible to define a variable in a programmatic powershell instance?
Upvotes: 0
Views: 804
Reputation: 7638
I'm pretty sure you just need to use AddParameter or AddArgument after adding the Get-ClusterResource
command to the pipeline. AddParameter on MSDN.
Once you have the first pipeline added (only a single command in this case), use var result = ps.Invoke();
, yank the required info from the result.Members collection, and use it to AddParameter or AddArgument after adding the Get-ClusterGroup
Then continue to use addCommand
to fill in the rest of the pipeline.
The Powershell Invoke method has an example on msdn
(copy and pasted for posterity):
// Using the PowerShell object, call the Create() method
// to create an empty pipeline, and then call the methods
// needed to add the commands to the pipeline. Commands
// parameters, and arguments are added in the order that the
// methods are called.
PowerShell ps = PowerShell.Create();
ps.AddCommand("Get-Process");
ps.AddArgument("wmi*");
ps.AddCommand("Sort-Object");
ps.AddParameter("descending");
ps.AddArgument("id");
Console.WriteLine("Process Id");
Console.WriteLine("------------------------");
// Call the Invoke() method to run the commands of
// the pipeline synchronously.
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine("{0,-20}{1}",
result.Members["ProcessName"].Value,
result.Members["Id"].Value);
} // End foreach.
Upvotes: 1