【问题标题】:Powershell output to PHP variable using shell_exec使用 shell_exec 将 Powershell 输出到 PHP 变量
【发布时间】:2017-02-17 12:58:53
【问题描述】:

我有一个输出视频文件持续时间的 powershell 脚本。运行这个脚本会给我预期的结果。

$Folder = 'C:\my\path\to\folder'
$File = 'sample1_1280_720.mp4'
$LengthColumn = 27
$objShell = New-Object -ComObject Shell.Application 
$objFolder = $objShell.Namespace($Folder)
$objFile = $objFolder.ParseName($File)
$Length = $objFolder.GetDetailsOf($objFile, $LengthColumn)
Write-Output $Length

在一个 php 文件中,我试图将此输出保存到一个变量中。

<?php
$var = shell_exec("powershell -File C:\my\path\to\psFile.ps1 2>&1");
echo "<pre>$var</pre>";
?>

我从 shell_exec 得到的字符串输出是你从 cmd 启动 powershell 时看到的文本。 Windows PowerShell 版权所有 (C) 2016 微软公司。保留所有权利。 有关如何提取视频时长的任何建议?

【问题讨论】:

  • 如果在shell_exec() 的PowerShell 命令中添加-NoLogo 会发生什么?
  • "powershell -NoLogo -File ..." - 给出相同的输出
  • 这表明shell_exec() 处理您传递的命令行的方式有点……奇怪。如果您在脚本中添加代码以将结果输出到文件中,该文件是否已创建并包含您期望的内容?
  • 是的,这是我已经成功测试过的备份计划。使用| Out-File -FilePath C:\... -Append 进行管道传输。结果如果不存在则创建一个文件,否则追加。

标签: php powershell shell-exec


【解决方案1】:

使用你的 PS 代码

$Folder = 'C:\my\path\to\folder'
$File = 'sample1_1280_720.mp4'
$LengthColumn = 27
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace($Folder)
$objFile = $objFolder.ParseName($File)
$Length = $objFolder.GetDetailsOf($objFile, $LengthColumn)
$Length

我可以使用 PS -File-Command 获取文件长度。我添加了一些您可能想要或需要的其他标志。您不需要使用重定向 2&gt;&amp;1 将变量从 PS 获取到 PHP。这很可能是您获得徽标的原因。

function PowerShellCommand($Command)
{
    $unsanitized = sprintf('powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -Command "%s"', $Command);

    return shell_exec($unsanitized);
}

function PowerShellFile($File)
{
    $unsanitized = sprintf('powershell.exe -NonInteractive -NoProfile -ExecutionPolicy Bypass -File "%s"', $File);

    return shell_exec($unsanitized);
}

// Can use relative paths
echo PowerShellCommand("./psFile.ps1");
// Be sure to escape Windows paths if needed
echo PowerShellFile("C:\\my\\path\\to\\folder\\psFile.ps1");

以所有三种方式返回 $Length 对我有用

$Length
return $Length
Write-Output $length 

【讨论】:

  • 太棒了!正是将 Windows 路径和-ExecutionPolicy Bypass 一起转义才成功。我已经单独尝试过它们,但没有一起尝试过。谢谢你:)
猜你喜欢
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 2017-06-06
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
相关资源
最近更新 更多