1

Here is my code. The first two options work but not the third. I am not sure what I am doing wrong. I am a bit of a newbie to powershell. Thanks.

$opt = Read-Host "Type 1 to login | Type 2 to disconnect | Type 3 to Exit"
write-host $opt

If ($opt -eq '1') {
$user = "myusername"

$UserCredential = Get-Credential -credential $user

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection

Import-PSSession $Session
}

ElseIf ($opt -eq '2') {
Get-PSSession | Remove-PSSession
} 

ElseIf ($opt -eq '3') {
Exit
}
6
  • 3
    What about it isn't working? What are you expecting it to do? Commented Jul 2, 2015 at 21:13
  • 2
    Does this code placed in .ps1 file? In that case Exit only exit that .ps1 file, not PowerShell itself. Commented Jul 2, 2015 at 21:23
  • I am trying to have it exit the script as well as close the shell. Commented Jul 2, 2015 at 23:28
  • Run the file on the PowerShell.exe command line and it will do what you want. If you run PowerShell and then ran the script from within, it won't close the shell. Commented Jul 3, 2015 at 2:31
  • I am confused between running the file on the PowerShell.exe command line and running powershell. If I run PowerShell is that not a shell with a command line? Commented Jul 3, 2015 at 3:40

1 Answer 1

2

If you really, really want to close the shell then rather than use exit, use this instead:

$Host.SetShouldExit(0)

Thanks to @PetSerAl for point out this option to gracefully shutdown the PowerShell process rather than just kill it with Stop-Process $pid.

BTW anybody else that stumbles upon your script might find it rude that you closed their shell. Perhaps 3 should be simply exit script and 4 is exit and close shell?

Sign up to request clarification or add additional context in comments.

2 Comments

Is not it will be better to allow PowerShell to exit gracefully? $Host.SetShouldExit(0)
That does have the advantage of allowing you to set the exit code. Then again, I suspect the OP doesn't care about an exit code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.