Running PowerShell from .NET Core - Command Not found
The problem is actually a compatibility issue with the edition being passed. You can view this by getting the Runspace's SessionStateProxy's error value:
var err=run.SessionStateProxy.PSVariable.GetValue("error");
It will reveal that there is an issue with the edition:
Module 'C:\windows\system32\WindowsPowerShell\v1.0\Modules\CIMCmdlets\CIMCmdlets.psd1' does not support current PowerShell edition 'Core'. Its supported editions are 'Desktop'. Use 'Import-Module -SkipEditionCheck' to ignore the compatibility of this module.
This provides the solution. There is not a way to do this with the InitialSessionState's ImportPSModule so try the following:
using System.Management.Automation;using System.Management.Automation.Runspaces;
InitialSessionState _initialSessionState = InitialSessionState.CreateDefault2();_initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;var script="$service = Get-CimInstance -ClassName Win32_Service -Filter \"name = 'MyNewService\'\";$service.DisplayName";using (var run = RunspaceFactory.CreateRunspace(_initialSessionState)){ run.Open(); var ps = PowerShell.Create(run); ps.AddCommand("Import-Module"); ps.AddParameter("SkipEditionCheck"); ps.AddArgument("CIMcmdlets"); ps.Invoke(); var err = run.SessionStateProxy.PSVariable.GetValue("error"); System.Diagnostics.Debug.WriteLine(err);//This will reveal any error loading ps.Commands.AddScript(script); var results = ps.Invoke(); run.Close(); return results;}