PSSession in script

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

## SHOW WHEN REMOTE SESSIE HAS ENDED
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,

Troy

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?

“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.

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

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.

Exactly my problem :slight_smile:

Thanks for thinking along Dave!

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

## some scripting

## ask for remote session part

    if ($DoSession -eq "Y")
        {
        cls
        $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!

Regards,

T.O.