c ++ createprocess powershell as admin,隐藏并且不要等待它

c++ createprocess powershell as admin, hidden and dont wait for it

这就是我所拥有的,在没有命令的情况下启动 powershell.exe 并在它之后直接关闭。 为什么它不起作用?

int main(int argc, char *argv[])
{

[...]
CreateProcess( NULL,   // No module name (use command line)
    "powershell.exe -command \".C:\test\t.ps1\"   ",      
[...]
        &si,            // Pointer to STARTUPINFO structure
        &pi );          // Pointer to PROCESS_INFORMATION structure

return 0;
}

在正常的 cmd 中,命令如下所示:

powershell -command ".c:\test\t.ps1"

在文件中这一行,如果你想测试它:

write-host "hello world" |out-file C:\test\hi.txt

应该在控制台中写入 hello world 并在文件夹中创建 hi.txt

命令行应该是:

CreateProcess(NULL, // No module name (use command line)
    "powershell.exe -command \"& {C:\test\t.ps1}\"",  

CreateProcess(NULL, // No module name (use command line)
    "powershell.exe -file C:\test\t.ps1",  

一般情况下,除非退出代码对您很重要,否则使用 -File 执行脚本。如果是,请使用 -Command,因为 -File 存在错误,即使出现错误,它也总是 returns 0(成功)。

如果要执行 powershell.exe 以提示提升,请改用 ShellExecute API。为lpOperation传入"RunAs",你可以用nShowCmd参数指定一个隐藏的window。