Nominate our 2022 Qt Champions!

Running commands that are part of the CMD shell with QProcess?

  • Hey,

    I need to execute a command on Windows, which is part of the CMD shell. So it doesn't have its own file in C:\Windows\system32, it is only available within cmd.exe.

    I've tried simply using:
    @QProcess process;
    where command is the command I'm trying to execute, however it returns an error that the file cannot be found.

    Is there any way to achieve this? Using cmd.exe /C command does not return an error, however it seems the command isn't executed. And simply using cmd.exe command makes the program hang.

    Thanks in advance!

  • Hi Qub1,
    did you try to call cmd.exe with command args like the this?
    process.start("cmd.exe command");

  • Hi, "cmd.exe command" would work if you'd launch cmd.exe using MSVC's system() call, but Qt uses some exec... flavor.
    So you need to spell out the whole enchilada, for example, say you want to save the path env. variable to a file to in C:, you can do it like this:
    process.start("cmd.exe",QStringList("/c echo %path% > c:\path.txt"));

  • Okay I will try that and edit this post, thanks!

  • I've tried that and it did not work.
    My current code is this:
    @bool createSymbolicLink(const int &type, const QString &linkPath, const QString &targetPath) {
    QString arguments = "/C mklink ";
    arguments += "/D ";
    arguments += """ + QDir::toNativeSeparators(linkPath) + "" "" + QDir::toNativeSeparators(targetPath) + """;
    QProcess mklink;
    mklink.start("cmd.exe", QStringList(arguments));

    return mklink.waitForFinished();

    It does return true, so the program executed, however the command isn't executed (I've tested).

  • Hi when I do the mklink command on my Windows 7, I have to do it using an administrator cmd.exe window, i.e. I think the mklink always requires administrator rights. So check that you start your Qt app as administrator.

    Also you can do a qDebug() << arguments; before to mklink.start just to see the command line.

Log in to reply