问题描述
尝试在php中运行以下命令以运行powershell命令...
Trying to run the following command in php to run powershell command...
以下作品:
$output = shell_exec(escapeshellcmd('powershell get-service | group-object'));
我不能像这样运行它:
$output = shell_exec('powershell get-service | group-object');
它不会通过管道|字符
但是如果我尝试运行:
$output = shell_exec(escapeshellcmd('powershell get-service | where-object {$_.status -eq "Running"}'));
我没有输出.
以下内容:
$cmd = escapeshellcmd('powershell get-service | where-object {$_.status -eq "Running"}');
返回:
powershell get-service ^| where-object ^{^$_.status -eq ^"Running^"^}
关于为什么发生这种情况以及如何解决此问题的任何建议?
Any suggestions on why this is happening and how to fix this?
我也可以将其作为.ps1脚本运行,但我希望能够将$ var传递给它.
Also I could run it as .ps1 script but I want to be able to pass $var to it.
推荐答案
尽管我没有任何PHP经验,但我还是会tab一口.
I'll take a stab although I have no PHP experience whatsoever.
我感觉正在发生的事情是您的管道字符是由命令外壳而不是PowerShell解释的.例如,如果您在cmd.exe命令提示符下运行以下命令:
I have a feeling that what's happening is your pipe character is being interpreted by the command shell instead of PowerShell. For example if you ran the following at the cmd.exe command prompt:
dir /s | more
第一个命令的输出将通过管道传递到第二个命令的输入,就像您在PowerShell中所期望的那样.
The output of the first command gets piped to the input of the second just like you'd expect in PowerShell.
转义字符串只会使问题变得更糟,因为您以某种方式转换字符串,因此PowerShell不知道如何对其进行转义.
Escaping the string will only make the problem worse because you're transforming the string in such a way that PowerShell has no idea how to unescape it.
尝试将原始PowerShell表达式括在如下报价中:
Try enclosing your original PowerShell expression in a quote like the following:
$output = shell_exec('powershell.exe -c "get-service | group-object"');
或者最好是看起来像有一个 exec ()函数不会通过命令外壳.这可能会更好.
Or preferably, it looks like there's an exec() function that does not go through the command shell. This might work better.
$output = exec('powershell.exe -c get-service | group-object');
这篇关于PHP Powershell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!