4

I am trying to restart iis remotely (Windows Servr 2012) from my local machine (Windows 7). The below command in command line doesn't work to restart IIS;

    iisreset servername /restart

but the below command works fine when I tried in command line.

    psexec iisreset \\servername /restart

Now the issue is when I try with below code in C#,

    Process process = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = "\C psexec iisreset \\servername /restart";
    startInfo.RedirectStandardOutput = true;
    startInfo.UseShellExecute = false;
    process.StartInfo = startInfo;
    process.Start();
    // capture what is generated in command prompt
    var output = process.StandardOutput.ReadToEnd();

If I give any other arguments in the above code like 'ipconfig', it gives me the expected output. But when I try with psexec, it gives empty output. But it works well when tried in command prompt.

I have also tried by using 'psexec.exe' in the filename and by removing '\C psexec' in the arguments. But still no luck.

Could you please anyone help me to resolve this?

Thanks in Advance.

user28
  • 249
  • 2
  • 7
  • 20
  • change startInfo.Arguments = "\C .... to startInfo.Arguments = @"\C.... see https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx – BugFinder Jul 31 '17 at 07:07
  • Thanks for the response. Still I am getting "The System cannot find the file specified" output but not the expected one. – user28 Jul 31 '17 at 07:47

4 Answers4

2

I have found that when using PSexec like this that you Shouldn't use CMD.exe, and you need to ensure that you have the full path to psexec. Even if it is in the same directory as your application exe.

//Assume that psexec.exe is in same location as application
//Get directory of running applications
String AppPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).Replace("file:\\","");

//Set up start infor details
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = false;

//Combine path of running app
startInfo.FileName = Path.Combine(AppPath, "psexec.exe");
startInfo.Arguments = "\\servername c:\path\to\iisreset  /restart";

//Execute
Process nProc = Process.Start(startInfo);
nProc.Start();
jason.kaisersmith
  • 8,712
  • 3
  • 29
  • 51
  • Thanks for the response Jason. But still I am getting "The System cannot find the file specified" output but not the expected one. – user28 Jul 31 '17 at 07:47
  • I changed the servername to be the first parameter, and you might need to the full path to iisreset on the remote server. See also this: https://stackoverflow.com/questions/21027559/process-start-in-windows-system32-folder – jason.kaisersmith Jul 31 '17 at 07:57
1

I hope u need to provide the domain admin credentials to it.

private int ExcecuteCommand(string command, string fileName, bool getResult, string timeout = null)
{
   try
     {
        var secure = new SecureString();
        foreach (char c in txtAdminPassword.Text)
        {
          secure.AppendChar(c);
        }
        System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
        pProcess.StartInfo.Domain = txtDomainName.Text;
        pProcess.StartInfo.UserName = txtUser.Text;
        pProcess.StartInfo.Password = secure;
        pProcess.StartInfo.FileName = fileName;// AppDomain.CurrentDomain.BaseDirectory + @"PSTools\PsExec.exe"; ;
        //pProcess.StartInfo.Arguments = string.Format(@"\\{0} -i -s -accepteula  ipconfig /all", ipAddress);
        //pProcess.StartInfo.Arguments = string.Format(@"\\{0} -accepteula netstat -ano",ipAddress);
        //pProcess.StartInfo.Arguments = string.Format(@"\\{0} -accepteula -i CheckURLConnectivity", ipAddress);
        //pProcess.StartInfo.Arguments = string.Format(@"\\{0} -accepteula  ping {2}", ipAddress, AppDomain.CurrentDomain.BaseDirectory + @"Installer\CheckURLConnectivity.exe","10.10.10.35");
          //pProcess.StartInfo.Arguments = string.Format(@"\\{0} -accepteula cmd /c type C:\ServiceLog.txt", ipAddress);
         pProcess.StartInfo.Arguments = command;//string.Format(@"\\{0} -accepteula -c -f {1}", compName, AppDomain.CurrentDomain.BaseDirectory + @"Installer\CheckURLConnectivity.exe");
        pProcess.StartInfo.UseShellExecute = false;
        Process.StartInfo.RedirectStandardInput = true;
        pProcess.StartInfo.RedirectStandardOutput = true;
        pProcess.StartInfo.RedirectStandardError = true;
        pProcess.StartInfo.CreateNoWindow = true;
        logger.log("Query " + command);
        pProcess.Start();
        if (timeout == null)
           pProcess.WaitForExit();
        else
           pProcess.WaitForExit(Convert.ToInt32(timeout));

         string strOutput = string.Empty;

          if (pProcess.HasExited == true && pProcess.ExitCode != 0)
            {
              string _errorMessage = GetWin32ErrorMessage(pProcess.ExitCode);
                pProcess.Kill();
               return pProcess.ExitCode;
            }
            else
              return 0;
      }
      catch (Exception)
       {
         return -1;
       }
 }
Ravi Kanth
  • 1,182
  • 13
  • 38
1

IISreset requires elevated privilege to work.So you have to use the -h switch with psexec

-h If the target system is Vista or higher, has the process run with the account's elevated token, if available.

    Process process = new Process();
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.FileName = "psexec.exe";
    startInfo.Arguments = "-h iisreset \\servername /restart";
    startInfo.RedirectStandardOutput = true;
    startInfo.UseShellExecute = false;
    process.StartInfo = startInfo;
    process.Start();
    // capture what is generated in command prompt
    var output = process.StandardOutput.ReadToEnd();
Rohith
  • 5,527
  • 3
  • 27
  • 31
1

Thank you all for your valuable response. It works fine with below code :)

    startInfo.FileName = @"C:\Windows\Sysnative\PsExec.exe";
    startInfo.Arguments = "iisreset \\servername /restart";

Reference: Process.Start in C# The system cannot find the file specified error

user28
  • 249
  • 2
  • 7
  • 20