如何在C ++上以管理员身份运行cmd命令

时间:2019-01-12 18:38:42

标签: c++ windows cmd

我想制作一个在cmd中运行命令的程序,但是作为管理员,但是我很难理解如何做。

我尝试更改程序启动属性以以管理员身份启动,但仍然无法正常工作,当我调用system()时,它不是管理员。

我尝试了这个解决方案,看到了here

system("runas /user:<admin-user> \"program.exe\"");

但是我不理解我应该如何用它来运行命令:

system("runas /user:<admin-user> \" COMMAND HERE? \"");

当我尝试在cmd中运行解决方案时,出现错误,提示未找到特定文件

此外,我正在尝试避免CreateProcess来执行此项目。 谢谢

2 个答案:

答案 0 :(得分:2)

您必须制作自己的system。这样的东西就足够了:

BOOL RunAsAdmin( LPCTSTR lpFile, LPCTSTR lpParameters, HWND hWnd ) {
    BOOL                retval;
    SHELLEXECUTEINFO    sei;
    ZeroMemory ( &sei, sizeof(sei) );

    sei.cbSize          = sizeof(SHELLEXECUTEINFO);
    sei.hwnd            = hWnd;
    sei.fMask           = SEE_MASK_FLAG_DDEWAIT | SEE_MASK_FLAG_NO_UI;
    sei.lpVerb          = TEXT("runas");
    sei.lpFile          = lpFile;
    sei.lpParameters    = lpParameters;
    sei.nShow           = SW_SHOWNORMAL;
    retval = ShellExecuteEx( &sei );
    // or try as the normal user ... remove if that's not an option
    if( !retval ) {
        sei.lpVerb = TEXT("open");
        retval = ShellExecuteEx( &sei );
    }

    return retval;
}

答案 1 :(得分:0)

您可能应该使用CreateProcessAsUser,但是由于您希望避免使用select Month, 'Most Frequent' from ( select *, row_number() over (partition by Month order by Frequency desc) rnk from ( SELECT MONTH(b.BookingStartDateTime) AS 'Month', f.FacilityDesc AS 'MOST FREQUENT', count(*) as 'Frequency' FROM Booking b INNER JOIN Facility f ON b.FacilityID = f.FacilityID WHERE YEAR(b.BookingStartDateTime) = 2017 GROUP BY MONTH(b.BookingStartDateTime), f.FacilityDesc ) rnk ) a where rnk = 1 order by month desc ,因此您可能也不想使用它。

要使用with rnk as ( SELECT MONTH(b.BookingStartDateTime) AS 'Month', f.FacilityDesc AS 'MOST FREQUENT', count(*) as 'Frequency' FROM Booking b INNER JOIN Facility f ON b.FacilityID = f.FacilityID WHERE YEAR(b.BookingStartDateTime) = 2017 GROUP BY MONTH(b.BookingStartDateTime), f.FacilityDesc ) select Month, 'Most Frequent' from rnk where exists( select Month, freq from ( select Month, max(Frequency) freq from rnk group by Month ) a where a.Month = rnk.Month and a.freq = rnk.Frequency ) order by Month desc 来执行此操作,您想创建一个包含要执行的完整命令的字符串,然后将其传递给CreateProcess,此命令按以下一般顺序进行:

system