PsExec启动后,C#在远程计算机上运行批处理文件

时间:2011-04-13 03:16:23

标签: c# file batch-file psexec

基本上,我正在尝试运行在远程计算机上复制的批处理文件,顺便说一下,这是我第一次尝试编码,所以请好好但是如果你想要批评它,我还在学习语言,并且不得不花费3个小时来达到这个目标,感谢上帝为谷歌,大声笑。

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void cleanerBtn_Click(object sender, EventArgs e)
        {
            //Copying Batch File to Remote Host
            string fileToCopy = "C:\\Clean.bat";
            string newLocation = hostName.Text;
            string newFile = (newLocation + "\\clean.bat");

            System.IO.File.Copy(fileToCopy, newLocation);

            //Run PsExec
            string psExec = "psexec -s "+newLocation+" cmd";
            System.Diagnostics.Process.Start("CMD.exe", psExec);

            //Run Batch File using PsExec


            //Removing Batch File from Remote Host
            System.IO.File.Delete(newFile);

        }

    }
}

提前致谢。

2 个答案:

答案 0 :(得分:2)

来自PSExec帮助:

-c将指定的程序复制到远程系统            执行。如果省略此选项,则应用程序            必须位于远程系统的系统路径中。

使用该标志使PSExec将要执行的批处理文件复制到远程系统并运行它。您不必编写额外的代码来执行此操作。

基本上你想做:

psexec \\server cmd.exe /c file_you_want_to_run.bat

答案 1 :(得分:0)

尝试使用/ C运行CMD.exe。从cmd.exe帮助:

  

/ C执行string指定的命令,然后终止

需要将/ C附加到psExec的内容:

System.Diagnostics.Process.Start("CMD.exe", "/C " + psExec);

我相信你会得到预期的结果。如果没有,您可能希望确保psexec.exe位于PATH环境变量中的目录中。

此外,您可能有兴趣查看ProcessStartInfo以指定可为执行过程设置的其他不同参数。

相关问题