Home > Back-end >  How do I implement an if statement for true or false? with the outcome of a PowerShell command
How do I implement an if statement for true or false? with the outcome of a PowerShell command

Time:10-27

The title might be a bit confusing because I don't know how to ask something like this if someone knows a better title let me know.

So what i did here is made a application that will give me all the users that are enabled. The problem is I don't know how i can get that data and use it further in my code. because I want to delete all the inactive ones but keep the active ones and with the active ones I will go on with my project.

So, for short, the question is how do I use/get the outcome of the command and go further with my application?

static void Main(string[] args)
{
    GetUserList();
}

public static string GetUserList()
{
    SelectQuery query = new SelectQuery("Win32_UserAccount");
    ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
    
    foreach (ManagementObject User in searcher.Get())
    {
        Process cmd = new Process();
        cmd.StartInfo.FileName = $@"powershell ";
        cmd.StartInfo.Arguments = $@"Get-LocalUser -Name {(string)User["Name"]} | Where-Object Enabled";
        cmd.StartInfo.RedirectStandardInput = true;
        cmd.StartInfo.RedirectStandardOutput = true;
        cmd.StartInfo.CreateNoWindow = true;
        cmd.StartInfo.UseShellExecute = false;
        cmd.Start();
        cmd.WaitForExit();
    }
    
   return null;
}  

This is one of the outcomes

If anyone knows a better way to do this or knows how to answer my question please let me know.

Thanks.

EDIT

Thanks to @mklement0.

(Get-LocalUser -Name {(string)User["Name"]}).Enabled

With this i can get a True or False out of every user.

CodePudding user response:

Generally, you're better off using an in-process solution based on the PowerShell SDK. Apart from being faster, it also allows you to get back typed data (rather than strings via stdout).

With your current approach, which requires creating a PowerShell child process in each iteration, use the following to get a (stringified) Boolean value as output for each user, i.e., "True" or "False", which indicates whether that user is enabled or not.

cmd.StartInfo.Arguments = $@"(Get-LocalUser -Name {(string)User[""Name""]}).Enabled"
  • Related