我对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运行它,脚本会运行,但输出中没有文件数据。
造成这种情况的原因是什么?
答案 0 :(得分:0)
这是一个允许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脚本的整个生命周期内都会维护该环境。