0

I need to run a command into CMD window and want to get result into a variable. I used below code to do the same but the out put is incorrect

        var proc = new Process
        {
            StartInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = " wmic.exe /node:(computername or ip address) computersystem get username ",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = true
            }
        };

        proc.Start();
        string line = "";
        while (!proc.StandardOutput.EndOfStream)
        {
            line += (line.Length > 0 ? "-----" : "") + proc.StandardOutput.ReadLine();
        }

        proc.WaitForExit(); 

Out put

Microsoft Windows [Version 6.1.7601]-----Copyright (c) 2009 Microsoft Corporation.  All rights reserved.----------C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0>

But when i run this command into CMD window it shows the current logged in users name.

Can any one help me to solve the issue.

Note :- The given command is used to get the current logged in users name on network system by using it's IP Address.

2

2 Answers 2

3

What you need is the /c option for cmd

C:\>cmd /?
Starts a new instance of the Windows command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates

I would question the need for cmd.exe here. You can just invoke wmic directly as below

var proc = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "wmic.exe",
        Arguments = "/node:localhost computersystem get username ",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

proc.Start();
string line = "";
while (!proc.StandardOutput.EndOfStream) {
    line += (line.Length > 0 ? "-----" : "") + proc.StandardOutput.ReadLine();
}

proc.WaitForExit();
Sign up to request clarification or add additional context in comments.

Comments

0

Why would you go to the trouble of invoking a commandline tool and parsing its results if System.Management has all the classes you need to obtain the information in-process and managed?

var ip = "127.0.0.1";
var scope = new ManagementScope(
    String.Format("\\\\{0}\\root\\cimv2", ip),
    new ConnectionOptions { Impersonation = ImpersonationLevel.Impersonate });
scope.Connect();

var users = new ManagementObjectSearcher(
    scope,
    new ObjectQuery("Select * from Win32_LoggedonUser"))
        .Get()
        .GetEnumerator();

while(users.MoveNext())
{
        var user =  users.Current["antecedent"];
        var mo = new ManagementObject(new ManagementPath(user.ToString()));

        try
        {
            var username = mo.Properties["name"];
            Console.WriteLine("username {0}", username.Value);
        }
        catch
        {
            Console.WriteLine(mo);
        }
}

All you have to do is create a ManagementScope and then use the ManagementObjectSearcher to run any WMI Query Language statement by using one of the available WMI Classes.

If you have a working wmic call you can always add /TRACE:ON so you can inspect the calls being made. Use wmic /? to see the aliasses.

5 Comments

I've added System.Management Name space into my code and tried your code but it troughs error {the type or namespace name ManagementScope could not be found}.
Change in reference solve above issue but it troughs error {Not Found} at below line of code :- var username = mo.Properties["name"];
@AshishRathore That is strange. On which Operating System are you and which version of the .Net framework? Are you running this for your local machine or are you connecting to a remote box. If so, what OS is that remote box running? What is in user.ToString()? does it contain a username with domain and the serverpath it is on?
user.ToString() = "\\\\.\\root\\cimv2:Win32_Account.Domain=\"IDR-ITD-SS169\",Name=\"IUSR\"" Local System OS = Windows7 Remote System OS = Windows7
@AshishRathore for some reason even an administrator while being elevated is not allowed to get to some properties on some managementobjects. I tried to find a way to prevent using a try/catch block but I didn't find another solution, so try/catch it is .. ;(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.