在PHP上运行时,Powershell脚本输出为空


Powershell Script Outputs blank when run on PHP

我对PHP和Powershell都有点陌生。我制作了一个网站来运行powershell脚本,该脚本检查多个服务器文件目录并返回该目录中的项目。在网站上,它们显示在一个有组织的数据表上。

我的问题是,当php exec()调用脚本时,它会运行,但数据输出为空。为什么php运行脚本时会发生这种情况?

这是powershell文件。我甚至添加了一些凭据会话,认为这一定是凭据问题。

  Remove-PSDrive target: -ErrorAction SilentlyContinue
  $global:username = "domain'user"
  $global:password = ConvertTo-SecureString –String "MyPassword" –AsPlainText -Force
  $global:cred = new-object -typename       System.Management.Automation.PSCredential -argumentlist $global:username,  $global:password

   $output_Table = @()
   $today = get-date
   $html_output =@()
   $tableData=@()

  New-PSDrive -Name target -PSProvider FileSystem -Credential $global:cred -Root "''serverName'filedir" | Out-Null
 $tableData+= '<table><tr><th>First Feed</th><th>Updates:DAILY</th></tr> <tr><th>FileName</th><th>FileDate</th></tr>'
 foreach ($file in (ls target:)) 
 {GetFeed(-7)}
 $tableData +='</table>'
 Remove-PSDrive -Name target -Force

 $html_output += $tableData
 $html_output += '</div>'
 $html_output | Out-File "C:'xampp'htdocs'script_results.txt" -Encoding utf8
 $today | Out-file "C:'xampp'htdocs'script_TimeStamp.txt" -Encoding utf8

script_result.txt包含带有HTML标记的文件。PHP稍后将读取此内容并将其回显到html页面中。

调用此脚本的PHP代码如下。

<?php
  if(isset($_POST['submit'])){
  set_time_limit (300);
  $output = array();
  $return_code = 0;
  $last_line = exec('powershell.exe C:'xampp'htdocs'script.ps1  2>&1 ', $output, $return_code);
  } ?>

稍后会有一段代码来显示结果。再次,如果我自己运行powershell脚本,它会返回带有所需输出的script_result。如果PHP运行它,脚本就会运行,但输出中没有文件数据

是什么原因造成的?

这里有一个项目,允许PHP获得真正的Powershell并与之动态交互。在这里获取:https://github.com/merlinthemagic/MTS

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

$shellObj    = 'MTS'Factories::getDevices()->getLocalHost()->getShell('powershell');
$strCmd1   = 'Remove-PSDrive target: -ErrorAction SilentlyContinue';
$return1  = $shellObj->exeCmd($strCmd1);
$strCmd2   = '$global:username = "domain'user"';
$return2  = $shellObj->exeCmd($strCmd2);
//etc, etc

通过这种方式,您可以发出每个单独的命令并处理返回,如果是权限问题,则失败的命令将从Powershell返回错误消息。您可以对$shellObj发出任何您喜欢的命令,该环境在PHP脚本的整个生命周期中都得到维护。