php - 使用 shell_exec 将 Powershell 输出到 PHP 变量

标签 php powershell shell-exec

我有一个输出视频文件持续时间的 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 Microsoft Corporation。保留所有权利。 关于如何提取视频时长的任何建议?

最佳答案

使用您的 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>&1 将变量从 PS 获取到 PHP。这很可能是您获得 Logo 的原因。

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 

关于php - 使用 shell_exec 将 Powershell 输出到 PHP 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42298608/

相关文章:

python - 从 python 脚本解锁 Windows 中的文件

php - 浏览器挂起执行运行 Powershell 的 PHP

PHP 将带撇号的字符串传递给 shell_exec

php - 如何使用 PhpWord 读取 Doc 文件?

php - Bootstrap 3.x 的粘性页脚不起作用

php - Apple 生产推送服务通知问题

php - 在 PHP 中使用不可打印字符作为分隔符?

azure - PowerShell任务Azure DevOps版本的脚本路径

function - 将字符串或字符串数​​组传递给 Powershell 中的函数

php-如何在执行命令时从 linux 终端获取 shell_exec() 输出?