【问题标题】:Execute powershell command via php通过php执行powershell命令
【发布时间】:2015-04-08 14:45:21
【问题描述】:

我有以下问题:

我有一个 xampp 服务器正在运行,我希望它执行一个 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 但无法解决问题。 我错过了什么?

【问题讨论】:

  • Start 最喜欢打开 ps1 文件,就好像您双击它而不是运行脚本一样,您可以尝试将 Start 行更改为 Start /Wait C:\windows\system32\WindowsPowerShell\v1.0\Powershell.exe -file C:\xampp\htdocs\CSVconvert\sortieren.ps1Start /Wait Powershell -file C:\xampp\htdocs\CSVconvert\sortieren.ps1

标签: php windows powershell batch-file


【解决方案1】:

由于问题是环境,我认为您可能会从自动处理该方面的软件包中受益。这是一个允许 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);

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 就是这样。谢谢!
    • 当您手动运行它们时,您使用的是 Powershell IDE 还是 CMD ?我认为您正在使用 IDE,您在其中提供了额外的设置。尝试使用 CMD 测试 cmdline 以找出您需要的特殊设置。
    猜你喜欢
    • 2011-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2012-01-21
    相关资源
    最近更新 更多