Author Posts

March 23, 2016 at 4:22 am

Hi all,

Perhaps you can help me with the following challenge:
I want to run a PSSession command in a script, but I want the main script to continue ONLY when the PSSession has ended.

Write-Host "Starting remote session..."

$PSSession = New-PSSession "$Server" -Authentication Credssp -Credential $Credential
Enter-PSSession -Session $PSSession

Write-Host "Remote session ended"
# Continue script

When I try it like above, the script will continue and leaving the session open in the process. If anyone has an idea how to make the script wait before continuing, please let me know!

Thanks and regards,


March 23, 2016 at 5:36 am

Enter-PSSession is used for an interactive shell. In a script, you'd typically want to use Invoke-Command instead. What's your intention with this script? Do you want to have the caller doing things interactively in the remote session, then exit when they're done and have the script continue?

March 23, 2016 at 5:55 am

"doing things interactively in the remote session, then exit when they're done and have the script continue"

Exactly that.

I use Invoke for other stuff, which works perfectly. But I also want to be able to start an interactive session which interrupts the main script.

March 23, 2016 at 6:22 am

I've never tried that before. Will experiment a bit and see what I can find.

March 23, 2016 at 6:37 am

Doesn't seem to work. What's actually happening is the script runs to its completion, and _then_ you get dumped out to an interactive prompt from Enter-PSSession. It doesn't interrupt the script at all.

March 23, 2016 at 6:56 am

Exactly my problem 🙂

Thanks for thinking along Dave!

March 24, 2016 at 2:19 am

Think I might have found a way.
Have a look at my solution:

## some scripting

## ask for remote session part

    if ($DoSession -eq "Y")
        $DoSessionPS1 = $env:SystemRoot+"\temp\doremote.ps1"
        if (Test-Path $DoSessionPS1) {del $DoSessionPS1}
        "`$Credential = (Get-Credential $env:USERNAME)" >$DoSessionPS1
        "`$PSSession = New-PSSession $Server -Authentication Credssp -Credential `$Credential" >>$DoSessionPS1
        "Enter-PSSession -Session `$PSSession" >>$DoSessionPS1
        cmd.exe /c start Powershell.exe -NoExit -File $DoSessionPS1
    else {Write-Host "Operation Aborted" -BackgroundColor Red -ForegroundColor Yellow}
Read-Host "Press enter to continue..."
Get-PSSession |Remove-PSSession

Perhaps it's not very pretty, but it does the trick for now.
Again, thanks for thinking along!