这就是我所拥有的,不使用命令启动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存在一个错误,即使出现错误,该错误也始终返回0(成功)。

如果要执行powershell.exe来提示提升权限,请改用ShellExecute API。传递"RunAs"作为lpOperation,您可以使用nShowCmd参数指定一个隐藏的窗口。

10-07 14:12
查看更多