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.

Ashish Rathore
  • 2,546
  • 9
  • 55
  • 91
  • do you have to use `cmd`? you could just use `wimc` directly. also, .net has apis for the logged in user name. – Daniel A. White Dec 22 '15 at 13:35
  • Possible duplicate of [How do I redirect cmd ftp ls command output to a C# variable](http://stackoverflow.com/questions/33674991/how-do-i-redirect-cmd-ftp-ls-command-output-to-a-c-sharp-variable) – BendEg Dec 22 '15 at 13:37

2 Answers2

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();
Vikhram
  • 4,294
  • 1
  • 20
  • 32
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.

rene
  • 41,474
  • 78
  • 114
  • 152
  • 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}. – Ashish Rathore Dec 23 '15 at 06:04
  • Change in reference solve above issue but it troughs error {Not Found} at below line of code :- var username = mo.Properties["name"]; – Ashish Rathore Dec 23 '15 at 06:22
  • @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? – rene Dec 23 '15 at 08:18
  • user.ToString() = "\\\\.\\root\\cimv2:Win32_Account.Domain=\"IDR-ITD-SS169\",Name=\"IUSR\"" Local System OS = Windows7 Remote System OS = Windows7 – Ashish Rathore Dec 23 '15 at 13:35
  • @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 .. ;( – rene Dec 23 '15 at 14:30