多个CMD命令管理c++(或c#)

Multiple CMD commands Managed c++ (or c#)

本文关键字:c++ CMD 命令 管理 多个      更新时间:2023-10-16

嘿,我只是想知道这是否适用于运行多个CMD命令?我还没有测试过。

//multiple commands
System::Diagnostics::Process ^process = gcnew System::Diagnostics::Process();
System::Diagnostics::ProcessStartInfo ^startInfo = gcnew System::Diagnostics::ProcessStartInfo();
//startInfo->WindowStyle = System::Diagnostics::ProcessWindowStyle::Hidden;
startInfo->FileName = "cmd.exe";
startInfo->Arguments = "/C powercfg -attributes SUB_PROCESSOR 12a0ab44-fe28-4fa9-b3bd-4b64f44960a6 -ATTRIB_HIDE";
startInfo->Arguments = "/C powercfg -attributes SUB_PROCESSOR 40fbefc7-2e9d-4d25-a185-0cfd8574bac6 -ATTRIB_HIDE";
process->StartInfo = startInfo;
process->Start();

或者startInfo一次只能处理一个参数?如果是这样,我如何执行多个命令而不创建.bat文件并执行该文件。

这行不通。这段代码:

stratInfo->Arguments = "/C powercfg -attributes SUB_PROCESSOR 12a0ab44-fe28-4fa9-b3bd-4b64f44960a6 -ATTRIB_HIDE";
stratInfo->Arguments = "/C powercfg -attributes SUB_PROCESSOR 40fbefc7-2e9d-4d25-a185-0cfd8574bac6 -ATTRIB_HIDE";

不设置两个参数。它设置参数字符串,然后覆盖它。

如果你想运行两次,你必须这样做:

void RunProc(System::String ^arguments)
{
    System::Diagnostics::Process ^process = gcnew System::Diagnostics::Process();
    System::Diagnostics::ProcessStartInfo ^startInfo = gcnew System::Diagnostics::ProcessStartInfo();
    startInfo->FileName = "cmd.exe";
    startInfo->Arguments = arguments;
    process->StartInfo = startInfo;
    process->Start();
}
RunProc("/C powercfg -attributes SUB_PROCESSOR 12a0ab44-fe28-4fa9-b3bd-4b64f44960a6 -ATTRIB_HIDE");
RunProc("/C powercfg -attributes SUB_PROCESSOR 40fbefc7-2e9d-4d25-a185-0cfd8574bac6 -ATTRIB_HIDE");

当然,你会想要添加错误处理等,特别是在当前进程没有正确权限的情况下。

您编写的代码完成了它看起来要做的事情。它首先将Arguments设置为一个值,然后用另一个值覆盖它。因此,Start()只执行第二个命令。

我建议创建一个辅助函数(或方法):
void RunPowerCfg(System::String ^id)
{
    System::Diagnostics::Process ^process = gcnew System::Diagnostics::Process();
    System::Diagnostics::ProcessStartInfo ^startInfo =
        gcnew System::Diagnostics::ProcessStartInfo();
    startInfo->FileName = "cmd.exe";
    startInfo->Arguments = System::String::Format(
        "/C powercfg -attributes SUB_PROCESSOR {0} -ATTRIB_HIDE", id);
    process->StartInfo = startInfo;
    process->Start();
}
void main()
{
    RunPowerCfg("12a0ab44-fe28-4fa9-b3bd-4b64f44960a6");
    RunPowerCfg("40fbefc7-2e9d-4d25-a185-0cfd8574bac6");
}

根据您想要做的事情,您可能希望在启动process->WaitForExit()后调用它。