Hey, Scripting Guy! Is there a way to make a script stop itself if certain conditions aren’t met? Like say I’m going to copy files to a remote computer, but then the remote computer isn’t available. Can I write code that tells the script to just go ahead and quit at that point?
— WK, Palo Alto, CA
Hey, WK. This is one of the easiest questions we’ve ever had to answer: you can stop a script at any time by using a single line of code:
Wscript.Quit
That’s it; as soon as that line is executed, the script stops right then and there.
So how would you actually make use of this command? Well, let’s take your scenario, in which you try to connect to a remote computer and you fail; in that case, an error will be generated. You can then check the value of the Err object and if it’s anything other than 0 (0 means no error occurred) you can exit the script right then and there:
If Err <> 0 Then Wscript.Quit End If
Or maybe before quitting you might want to echo a message explaining why the script quit:
If Err <> 0 Then Wscript.Echo "Unable to contact remote computer; " & _ "the script will now quit." Wscript.Quit End If
For more information about the Quit method, see this portion of the Windows Script Host documentation on MSDN
0 comments