PHP 可执行文件,仅输出错误


PHP exec, output errors only

我正在使用PHP exec运行Powershell脚本来创建通过HTML表单提交的新用户。 我要做的是在网页上仅输出此命令的错误,以便任何 IT 团队成员都可以看到是否出了任何问题。 这是我所拥有的:

$psPath = 'c:''Windows''System32'WindowsPowerShell'v1.0''powershell.exe -version 5';
$psDIR = "d:''wamp64''www''includes''";
$psScript = "NewHire.ps1";
$runCMD = $psPath. ' -ExecutionPolicy RemoteSigned '.$psDIR.$psScript
$createuser = exec($runCMD.' 2>&1', $out);

当我做一个var_dump($out)时,它同时显示输出和错误。 我尝试将其更改为exec($runCMD.' &1', $out)但它仅显示输出。 如果我尝试exec($runCMD.' 2>', $out),它不会运行我的命令。 有没有办法只在$out变量中显示错误?

试试这个,

exec($runCMD."2>&1 1>/dev/null ",$out);

也许这可能会有所帮助

public static function exec_alt($cmd)
{
    exec($cmd, $output);
    if (!$output) {
        /**
         * FIXME: for some reason exec() returns empty output array @mine,'s machine.
         *        Somehow proc_open() approach (below) works, but doesn't work at
         *        test machines - same empty output with both pipes and temporary
         *        files (not we bypass shell wrapper). So use it as a fallback.
         */
        $output = array();
        $handle = proc_open($cmd, array(1 => array('pipe', 'w')), $pipes, null, null, array('bypass_shell' => true));
        if (is_resource($handle)) {
            $output = explode("'n", stream_get_contents($pipes[1]));
            fclose($pipes[1]);
            proc_close($handle);
        }
    }
    return $output;
}

如果您使用的是 Windows 7,则可能需要:

禁用用户帐户控制 (UAC)

用户帐户控制设置.exe

C:'Windows'System32'UserAccountControlSettings.exe 并选择"从不通知"

发现这仅适用于 stderr:

exec($runCMD.' >&2' , $out);