Get Local User from PowerShell

Viewed 51

I am trying to get the local users that are connected to a Microsoft account from my C# application.

PS C:\Users\MyUser> Get-LocalUser | Select Name, PrincipalSource

When I run this from cmd, I get the desired results. I tried to reproduce this in c#

using (PowerShell ps = PowerShell.Create())
                {
                    ps.AddCommand("Get-LocalUser | Select Name, PrincipalSource");
               
                    foreach (PSObject pso in ps.Invoke())
                    {
                        if (pso.Members["PrincipalSource"].Value != null)
                        {
                            
                        }
                    }
                }

This will return the User name but not the PrincipalSource, there are no return errors

1 Answers

Don't use Select, just return the whole object back to C#

using (PowerShell ps = PowerShell.Create())
{
    ps.AddCommand("Get-LocalUser");
               
    foreach (Microsoft.PowerShell.Commands.LocalUser lu in ps.Invoke())
    {
        if (lu.PrincipalSource != null)
        {
            // do stuff
        }
    }
}

If you don't have the module referenced then you can just use dynamic

foreach (dynamic lu in ps.Invoke())
Related