2017-02-17 88 views
2

我有一个PowerShell脚本输出视频文件的持续时间。运行这个脚本给了我预期的结果。Powershell输出到PHP变量使用shell_exec

$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。版权所有。关于如何提取视频持续时间的任何建议?

+1

如果你在'了shell_exec()''添加到-NoLogo'你的PowerShell命令会发生什么? –

+0

“powershell -NoLogo -File ...” - 给出相同的输出 – Thomas

+0

这表明''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>&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 
+0

非常好!这是将Windows路径和'-ExecutionPolicy Bypass'转移到一起的组合。我已经单独尝试过,但不是在一起。谢谢 :) – Thomas