Forum Discussion
PowerShell hosting in C#
Don't know if this is the correct place to post my question...
I want to use the PowerShell 7 cmdlet Get-ClusterResource in C# under Windows 11, like this:
using System.Collections.ObjectModel;
using System.Management.Automation;
namespace PSHosting;
class Program { static void Main()
{
using (var powerShell = PowerShell.Create())
{
powerShell.AddScript("Get-ClusterResource -Cluster 'WSFC1'");
Collection<PSObject> result = powerShell.Invoke();
}
}
I have the RSAT FailoverCluster Windows package installed.
When calling Get-ClusterResource in a PowerShell session, PowerShell uses the implicit remoting technique to create and load a proxy module for the original FailoverCluster module, and then execute the command on the remote computer.
At some point during my attemps to get a working Get-ClusterResource in my C# code, I included the following in the above code (before the using statement):
- A Set-ExecutionPolicy command that lets PowerShell execute arbitrary scripts (most probably required because module loading (see below) and/or implicit remoting would run .ps1 and/or .psm scripts contained in the FailoverCluster module folder)
- An Import-Module command that loads the FailoverCluster module into the current session
Interestingly, the above code still works in my environment after stripping the commands 1. and 2. above from the code, deleting the proxy module C:\Users\<UserName>\AppData\Local\Temp\remoteIpMoProxy_FailoverClusters_2.0.0.0_localhost_<ID>, and rebooting the computer.
My ultimate goal is to publish code like the above together with all required modules and other stuff so it can run successfully on a computer with stock Windows 11 installed only (single exception: .NET runtime matching my C# version is installed, so I don't need to distribute that too).
From what I think I know at the moment, this means that I need to:
- Include the FailoverCluster module folder in my publication, and
- Add the commands 1. and 2. above in my code (hopefully, referencing the FailoverCluster module works with a relative path)
Am I correct here, or do I miss something out?