Reputation: 1
I have a php server that generates a ps1(poweshell) script and manage remote computer. For example I have powershell script that looks like:
$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}
I run this script from php by:
shell_exec("powershell.exe -ExecutionPolicy RemoteSigned -File script.ps1")
Then I need to invoke second script, and want to use session created by first script. The question is how to leave remote session alive after first script ending. Maybe is there other solutions like using other languages instead of php?
Thanks
Upvotes: 0
Views: 2177
Reputation: 336
You can reuse/share a remote powershell session between multiple scripts with a global variable.
In the first script you create a remote sessin and store it in a global variable.
$Global:session = New-PSSession -ComputerName $remoteServer -credential $credential
In all other scripts you can use Invoke-Command
as follows:
Invoke-Command -Session $session -ScriptBlock {
/* Remote code */
}
Then you can run the scripts as follows:
$scripts = "create_session.ps1; script_1.ps1; script_2.ps1";
shell_exec("powershell.exe -Command @(\"$scripts\" )");
Upvotes: 2
Reputation: 68303
If you have Powershell V3 on the managed machines, you can use Disconnected Sessions, creating the session in the first script, then explicitly disconnection from it with Disconnect-PSSession. Then you can use Connect-PSSession in the second script to reconnect back to that same session.
Upvotes: 0