通过 php 执行 powershell 命令

Execute powershell command via php

我有以下问题:

我有一个 xampp 服务器 运行ning,我希望它执行 powershell。 php 触发包含以下代码的 .bat 文件:

@echo
cd C:\OpenBR\bin
start /WAIT br -algorithm FaceRecognition -compare C:\xampp\htdocs\upload C:\xampp\htdocs\DP C:\xampp\htdocs\results\result.csv


start  /WAIT C:\xampp\htdocs\CSVconvert\sortieren.ps1 

start  /WAIT C:\xampp\htdocs\CSVconvert\Removedouble.ps1

start  /WAIT C:\xampp\htdocs\CSVconvert\remove_path.ps1

start  /WAIT C:\xampp\htdocs\CSVconvert\remove_foo.ps1

start  C:\xampp\htdocs\CSVconvert\remove_quoatation.ps1

第一部分工作正常,直到我想执行 powershell "sortieren.ps1"。当我 运行 手动批处理时,它会执行并完成作业,当通过 php 触发时,它不会。 我在 x86 和 x64 shell 中都设置了 "Set-ExecutionPolicy Unrestricted"。 我只是感到困惑,因为普通的命令行可以工作而 powershell 不能,即使在将其设置为不受限制后也是如此。

我看过 executing a Powershell script from phpPowerShell on Windows 7: Set-ExecutionPolicy for regular users 但无法解决问题。 我错过了什么?

您 运行 在其中执行这些命令的会话没有与您使用 PowerShell 手动 运行 它们时相同的环境变量。您必须指定 powershell 可执行文件的绝对路径和您想要 运行 的脚本,以便找到它们。

start /WAIT C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe C:\xampp\htdocs\CSVconvert\sortieren.ps1

由于问题出在环境上,我认为您可能会受益于自动处理该方面的包。这是一个允许 PHP 获取真实 Powershell 并与之动态交互的项目。在这里获取:https://github.com/merlinthemagic/MTS

下载后您只需使用以下代码:

$shellObj    = \MTS\Factories::getDevices()->getLocalHost()->getShell('powershell');

$strCmd1   = 'first command from first script';
$return1  = $shellObj->exeCmd($strCmd1);

$strCmd2   = 'second command from first script';
$return2  = $shellObj->exeCmd($strCmd2);

您可以单独触发每个命令并处理 return,而不是触发单个脚本。您可以对 $shellObj 发出您喜欢的任何命令,该环境在 PHP 脚本的整个生命周期内得到维护。