2017-02-17 92 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