简体   繁体   中英

How can I shell_exec this powershell command to get the pid of a process?

I need to run this command from php within a shell exec but it doesn't work Im runing a node rtsp monitoring aplication from php so i need to get the pid of the node process every time it runs so when i close the window i can close the process so the cpu doesn't exceed it's limits.

I tried

Get-Process | Where-Object ProcessName -eq "node" | ForEach-Object Id

and

Get-Process | Where-Object { $_.ProcessName -eq "node" } | ForEach-Object { $_.Id }

both works in powershell but not in php

this is what i need to run

$cmd = "Get-Process | Where-Object ProcessName -eq 'node' | ForEach-Object Id";
        var_dump(shell_exec("powershell.exe -Command " . $cmd));

debugging returns null

var_dump(shell_exec('powershell.exe ' . $cmd));

PHP's shell_exec() function, as the name suggests, uses the host platform's native shell , which on Windows means that the given command line is passed to cmd.exe .

Therefore, if you want to pass metacharacters such as | through to PowerShell , you must quote them, so that cmd.exe doesn't interpret them: You typically do that by enclosing arguments in double quotes ( "..." ) or, less commonly, by quoting (escaping) individual characters with ^ .

The best approach in your case is to double-quote the entire PowerShell command using embedded double quotes in the command-line string passed (adapting the technique from your own comment on the question):

$cmd = "Get-Process | Where-Object ProcessName -eq 'node' | ForEach-Object Id";
var_dump(
 shell_exec("powershell.exe -Command " . '"' . str_replace('"', '\"', $cmd) . '"')
);

Note the str_replace() call, which ensures that any " chars. embedded in $cmd are properly escaped as \\" , even though that's not strictly necessary with the specific command in question.


Note that you can greatly streamline your code , in which case you could even get away without double-quoting.

$cmd = "(Get-Process -ErrorAction Ignore -Name node).Id";
var_dump(shell_exec("powershell.exe -Command " . $cmd));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM