首页 > 解决方案 > 使用 Qt 运行 Windows PowerShell 命令

问题描述

这篇文章之后,我打算在具有管理员权限的 Windows 10 上的 Qt 5.12.6 应用程序中运行此命令:

powershell -Command "agent.exe  -Verb runAs"

agent.exe的旁边是我的 Qt 应用程序可执行文件,即它的父目录是QCoreApplication::applicationDirPath().


另一篇文章的启发,我的 C++/Qt 代码如下所示:

m_agent = new QProcess(this);

QString agentName = "/agent.exe";
// "agent.exe" executable is next to application executable
QString agentPath = QCoreApplication::applicationDirPath() + agentName;
QStringList args = QStringList();
// I'm not sure how to compose `args`
args << "-Command"; // ?
args << agentPath; // ?
args << "-Verb"; // ?
args << "runAs"; // ?
m_agent->start("powershell ", args);

我的当前args,上面组成,没有启动agent.exe.

我的问题是:我应该如何args编写才能使用 Qt 运行我的 Windows PowerShell 命令?

标签: c++windowspowershellqtcommand-line

解决方案


一些观察有助于解决问题。

现在agent.exe使用以下代码以管理员身份运行:

QString agentName = "/agent.exe";
QString agentPath = QCoreApplication::applicationDirPath() + agentName;
QStringList args = QStringList();
args << "-Command";
args << "Start-Process";
args << agentPath;
args << "-Verb";
args << "runAs";
m_agent->start("powershell", args);

更新

或者,您可以按照@Botje 的建议执行此操作

QString agentName = "/agent.exe";
QString agentPath = QCoreApplication::applicationDirPath() + agentName;
QStringList args = QStringList();
args = QStringList({"-Command", QString("Start-Process %1 -Verb runAs").arg(agentPath)});
m_agent->start("powershell", args);

推荐阅读