C# 运行Power Shell命令并返回结果

public string ExecuteInstructions(string sCmd)
{
    try
    {
        Process mProcess = new Process();
        mProcess.StartInfo.UseShellExecute = false;
        mProcess.StartInfo.RedirectStandardOutput = true;
        mProcess.StartInfo.FileName = @"powershell.exe";//也可以打开自己写的.exe文件,加上路径和名字即可
        mProcess.StartInfo.Arguments = sCmd;
        mProcess.Start();

        string sResult = mProcess.StandardOutput.ReadToEnd();
        mProcess.WaitForExit();

        return sResult;
    }
    catch (Exception e)
    {
        using (StreamWriter outfile = new StreamWriter("PowerShellResult.txt", true))
        {
            return "异常:" + e.Message;
        }
    }
}

 

posted @ 2022-12-29 14:19  ckrgd  阅读(218)  评论(0编辑  收藏  举报