Robin Sparkles
Robin Sparkles

Reputation: 13

Using PowerShell command "Get-LocalGroup" in c#

when I try to use the PowerShell cmdlet "Get-LocalGroup" in my c# application it won't print out any output of this cmdlet on my console.

I've already included the Management.Automation NuGet. The build process works without problems. I also tried to start the built .exe with admin permissions in debug and release mode.

using System.Collections.ObjectModel;
using System.Management.Automation;

namespace RunPowershell
{
    class Program
    {
        static void Main(string[] args)
        { 
            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddScript("Get-LocalGroup");

                Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

                // loop through each output object item
                foreach (PSObject outputItem in PSOutput)
                {
                    if (outputItem != null)
                    {
                            System.Console.WriteLine("-"+outputItem.BaseObject);
                    }
                }
                System.Console.WriteLine("Hit any key to exit.");
                System.Console.ReadKey();
            }
        }
    }
}

I can't see a significant error in the debug window, but there's also no output of "Get-LocalGroup".

Upvotes: 1

Views: 496

Answers (1)

boxdog
boxdog

Reputation: 8432

The lack of output from Get-LocalGroup is due to the CPU targeting of your project. If it is x86 or Any CPU, then Get-localGroup won't work as it only works in an x64 host. You can see this in action if you open an x86 PowerShell console - it will complain there is no such command. You can also see the error listed in the PowerShellInstance.Streams.Error stream in your C# project.

Once you fix the targeting, then you need to take care of extracting/formatting the results manually, since Powershell stores these in a collection and not as simple properties. Check out a previous answer of mine on how to make life easier for yourself by converting the results to custom objects:

Dealing with CimObjects with PowerShell inside C#

Upvotes: 1

Related Questions