Reputation: 884
I have a powershell script that works like a menu. After making a choice, it starts another powershell script.
The other scripts are fairly large, and I have many points in the scripts where I need to abort that script and return back to the menu.
I call the other scripts using:
invoke-expression -Command "& '.\script.ps1'"
In the script itself, at various locations, I use the following command to break out of the script.
break script
This works well, as it terminates the script, but it does not return to the previous invoked script.
The break command with parameter means that it breaks to a label. If no label is present it will break out of the entire script. But given how I invoke the script currently, it sees everything as one big script and breaks out of everything.
In my subscript, I placed the following at the end of the file:
:End_Of_Script
and used break End_Of_Script but that fails the same.
So my question is boiling down to this: How can I invoke another script and at any point break out of that script and return back to the previous script without altering the complete structure of that script?
Here's a snippet of what the subscript is:
write-host "1. Choice A"
write-host "2. Choice B"
$choice = read-host "What choice?"
switch ($choice)
1
{
write-host "The choice is A"
}
2
{
write-host "The choice is B"
}
default
{
write-host "Invalid choice"
break script
}
get-childitem | foreach-object {
if( $_.Name -like "*test*")
{
break script
}
}
In my main script, the commands after invoke-expression ...
are never executed.
Upvotes: 1
Views: 899
Reputation: 1423
You can use exit
to do this.
The exit keyword is best used in functions, and when those functions are called in a script. It's a great way to terminate execution of functions.
reference PowerShell Exit Function & Code Execution | Pluralsight
If the script encounters an error and needs to exit, throw
can be used to better prompt the specific cause of the error.
Calling another script can be done with & $FilePath
, invoke-expression -Command "& '$FilePath'"
is a cumbersome and unnecessary usage.
Upvotes: 1