3

I am writing a powershell script to backup and restore databases. I am using forms to gather user input. At any point in the information gathering process, the user can hit "cancel".

To keep things tidy, I moved the form logic into separate functions. Is there a way to "exit" the entire script from within the function?

I tried putting the exit command inside the add_click event, but I get an exception error.

  # create Cancel button
  $CancelButton = New-Object System.Windows.Forms.Button
  $CancelButton.Location = New-Object System.Drawing.Size(160,320)
  $CancelButton.Size = New-Object System.Drawing.Size(75,23)
  $CancelButton.Text = "Cancel"
  $CancelButton.Add_Click(
  {$Looping=$False
   $RestoreFromFileForm.Close()
   exit
  })
  $RestoreFromFileForm.Controls.Add($CancelButton)
4
  • What's the error you are getting?
    – JNK
    Nov 16, 2011 at 16:22
  • "unhandled exception error" with a thousands lines of unintelligible goop.
    – datagod
    Nov 16, 2011 at 18:15
  • fixed your question title and removed the database tag as this has nothing to do with databases.
    – x0n
    Nov 16, 2011 at 19:20
  • Thanks x0n. I originally posted in dba.stackexchange, and it was moved here.
    – datagod
    Nov 17, 2011 at 14:35

2 Answers 2

7

You want to close everything when Cancel button is clicked right?

Then instead of exit, do:

[environment]::exit(0)

This will make sure that if the Cancel is pressed, the execution of the powershell script itself is stopped, rather than just trying to stop the form application alone. If there are parts of script that shouldn't be run after the form is cancelled, then go with this approach.

If you are in console and don't want the exit to close the shell, run the script as:

powershell .\script.ps1
1
  • Wow, that did the trick. Killed the whole ISE though....bit more than I was bargaining for.
    – datagod
    Nov 16, 2011 at 18:28
7

I think you probably want:

[System.Windows.Forms.Application]::Exit($null)

as manojlds's solution will kill the entire shell.

2
  • Yeah, but see that form is already being closed. OP seemed to hint that if the cancel button is clicked, anything after that in the powershell script should not be run.
    – manojlds
    Nov 16, 2011 at 19:26
  • yeah, but the comment on your answer told me he didn't want that. not your fault - if I could give you half the answer points, I would :)
    – x0n
    Nov 17, 2011 at 15:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.