Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

powershell

This is what I have, starting powershell.exe without the command and closing directly after it. why doesnt it work?

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;
}

in normal cmd the command would look like this:

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

and in the file this one-liner, if you want to test it:

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

should write hello world in the console and create hi.txt in the folder

like image 782
Marabunta Avatar asked Jan 17 '26 22:01

Marabunta


1 Answers

The command line should be either:

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

or

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

In general, for executing scripts use -File unless the exit code is important to you. If it is, use -Command because there is a bug with -File where it always returns 0 (success) even if there is an error.

If you want the execution of powershell.exe to prompt for elevation, use the ShellExecute API instead. Pass in "RunAs" for lpOperation and you can specify a hidden window with the nShowCmd parameter.

like image 162
Keith Hill Avatar answered Jan 20 '26 10:01

Keith Hill