0

I have a Function invokes a command that starts a new ps session on a remote server. The invoke command has an Exit clause however this is not exiting?

Function CreateID{

  Invoke-Command -Session $Script:sesh -ScriptBlock{
    Set-Location c:\
    Import-Module ActiveDirectory

    Try
    {
        If (Get-ADGroupMember "$Using:IDGroup" | Where-Object Name -match 
    "$Using:Computer")
        {
            Write-Host "Already in $using:IDGroup Exiting Script"
            Disconnect-PSSession -Session $Script:sesh
            Exit-PSSession
            Exit
        }
     }
     Catch
     { }
     Write-Host "Did not Exit"


    }

}

The Get-AD command works fine so where it should not display "did not exit" it does - how can i exit from a scriptblock in a remote ps session?

I am trying the disconnect session and Exit-pssession to see if they would do the same as simply exit but none of those are working.

I have also tried Break and no luck.

LDStewart
  • 117
  • 3
  • 11

3 Answers3

0

Ok so i figured this out - the ps session and invoke-command are red herrings. The basis of this is that you cannot Exit a Try/Catch statement.

i had to do this to get it to work - now it Exits. I just cannot use a Try/ Catch - if anyone knows how to exit a Try/Catch let me know!

#Try
#{
    If (Get-ADGroupMember "$Using:IDGroup" | Where-Object Name -match 
"$Using:Computer")
    {
        Write-Host "Already in $using:IDGroup Exiting Script"
        Disconnect-PSSession -Session $Script:sesh
        Exit-PSSession
        Exit
    }
 #}
 #Catch
 #{ }
LDStewart
  • 117
  • 3
  • 11
0

I don't know if this works for PSSession or not, and I don't have an environment to test it, but you can use this to exit powershell within a try catch

[Environment]::Exit(0)
HeedfulCrayon
  • 837
  • 6
  • 20
0

Try/Catch should work in an invoke-command. I don't usually invoke-commands to sessions, rather I use -ComputerName.

This worked fine for me:

invoke-command -ComputerName "MyDomainController" -ScriptBlock {
    try { get-aduser "ValidUser" } catch { "doh!" }
}

I just tried this as well and it also worked:

$sess1 = New-PSSession -ComputerName MyDomainController
invoke-command -Session $sess1 -ScriptBlock { try { get-aduser "ValidUser" } catch { "doh!" } }

If I change either of those "ValidUser" values to invalid users I see the "doh!" as well.

Perhaps it's because you're trying to end the session from within the session. You should deal with the output of the invoke-command or the function and then handle the session based on that.

Like using my lame example...

$sess1 = New-PSSession -ComputerName MyDomainController
$DoStuff = invoke-command -Session $sess1 -ScriptBlock { try { get-aduser "ValidUser" } catch { "doh!" } }
If ($DoStuff -eq "doh!") { Remove-PSSession $sess1 } else { $DoStuff }
mOjO
  • 98
  • 6