2013-02-15 27 views
0

我有一個生成ps1(poweshell)腳本並管理遠程計算機的php服務器。比如我有PowerShell腳本,看起來像:跨腳本重複使用/共享PowerShell遠程會話

$ip=192.168.137.25; 
$pw = convertto-securestring -AsPlainText -Force -String a 
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "$ip\admin",$pw 
$session = new-pssession $ip -credential $cred 
invoke-command -session $session -scriptblock {ls} 

我從PHP運行此腳本:

shell_exec("powershell.exe -ExecutionPolicy RemoteSigned -File script.ps1") 

然後我需要調用第二個腳本,想使用的第一個腳本創建的會話。 問題是如何在第一個腳本結束後讓遠程會話保持活動狀態。 也許有其他解決方案,如使用其他語言,而不是PHP?

感謝

回答

0

如果您對管理機PowerShell的V3,就可以使用已斷開的會話,在第一個腳本與斷開-PSSession將創建會話,然後明確地從它斷開。然後,您可以在第二個腳本中使用Connect-PSSession重新連接回相同的會話。

0

您可以在多個腳本之間重複使用/共享一個遠程PowerShell會話並使用全局變量。

在第一個腳本中,您創建了一個遠程sessin並將其存儲在一個全局變量中。

$Global:session = New-PSSession -ComputerName $remoteServer -credential $credential 

在所有其他腳本可以使用Invoke-Command如下:

Invoke-Command -Session $session -ScriptBlock { 
/* Remote code */ 
} 

然後你可以運行的腳本如下:

$scripts = "create_session.ps1; script_1.ps1; script_2.ps1"; 
shell_exec("powershell.exe -Command @(\"$scripts\")");