2012-06-26 56 views
0

代碼:PHP將名單從Powershell的成陣列

$exchangesnapin = "Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010"; 
$output = shell_exec('powershell '.$exchangesnapin.';"get-mailboxdatabase" 2>&1'); 
echo('<pre>'); 
echo($output); 
echo('</pre>'); 

結果:

Name       Server   Recovery  ReplicationType 
----       ------   --------  --------------- 
Mailbox Database 0651932265 EGCVMADTEST  False   None   
Mailbox Database 0651932266 EGCVMADTEST  False   None  

我試着用

echo($output[1]); 

結果是隻有一個字母 'N'。我相信它一次只取得一個字符的名稱列。

$output[1] is 'N', $output[2] is 'a'. 

有沒有什麼辦法可以讓郵箱列表進入數組?

+1

不是PHP將所有PowerShell輸出轉換爲字符串?您需要使用文本解析技術將其轉換爲PHP中的數組。 – ravikanth

回答

2

您試圖從PHP執行一個外部程序(powershell)並將輸出作爲一個數組。 爲了執行在PHP外部程序,你可以使用:使用過程控制

擴展(PC NTL,popen)給你更多的控制,但需要更多的代碼和時間。使用執行功能更簡單。

在這種情況下,使用exec()可以幫助您將數組中的powershell輸出存儲在數組中,該數組的每個索引都是來自powershell輸出的一行。

<?php 
$output = array(); // this would hold the powershell output lines 
$return_code = 0; // this would hold the return code from powershell, might be used to detect execution errors 
$last_line = exec("powershell {$exchangesnapin} get-mailboxdatabase 2>&1", $output, $return_code); 
echo "<pre>"; 
// print_r($output); view the whole array for debugging 
// or iterate over array indexes 
foreach($output as $line) { 
    echo $line . PHP_EOL; 
} 
echo "</pre>"; 
?> 

請注意,(如文檔說),如果你只是想呼應的PowerShell的輸出,你可以使用passthru()功能。使用exec()使用內存來存儲外部程序的輸出,但使用passthru不會使用此存儲,從而減少內存使用量。但是輸出不能用於進一步處理,並以某種方式發送到PHP標準輸出。

最後,請注意,外部程序執行需要仔細的數據驗證,以減少不必要的系統影響的風險。確保對構造執行命令的數據使用escapeshellarg()

+0

有了這個解決方案,我可以把它放到下拉菜單中。非常感謝你! – Mezzan