Author Posts

March 4, 2018 at 5:08 am

I have a Windows form that has a button that run a few functions:

$StartButton.Add_Click({
Test1
Test2
Test3
Test4
Test5
})

With each function there's an if statement that says if it's true then do something and if it's false to exit the script. If any part of any of the functions fails, I want to exit the script. The way I am currently exiting the script is with the exit command. Of course I get an unhandled exception because the form is still open. Is there a way for me to end my script and leave the form still open if an error occurs? I can only think of 2 ways to do this, but wanted to make sure if there was an easier way. The first way I could think of doing this is putting a $failure variable at the beginning of each function and evaluate if it's false to continue or return the function:

$failure=$false
$StartButton.Add_Click({
Test1
Test2
Test3
Test4
Test5
})

function Test1 {
If (Get-Process -Name chrome) {
do something
}
else {
$failure=$true
return}
}

function Test2 {
If ($failure -eq $false){
If (Get-Process -Name explorer) {
do something
}
else {
$failure=$true
return}
}
else {return}
}

function Test3 {
If ($failure -eq $false){
If (Get-ChildItem -Name "Documents") {
do something
}
else {
$failure=$true
return}
}
else {return}
}

function Test4 {
If ($failure -eq $false){
If (Get-ChildItem -Name "Desktop") {
do something
}
else {$failure=$true
return}
}
else {return}
}

function Test5 {
If ($failure -eq $false){
If (Get-LocalUser -Name administrator){
do something
}
else {$failure=$true
return}
}
else {return}
}

OR this which is better readablity:

$failure=$false

$StartButton.Add_Click({
If ($failure -eq $false) {
Test1
} else {return}
If ($failure -eq $false) {
Test2
} else {return}
If ($failure -eq $false) {
Test3
} else {return}
If ($failure -eq $false) {
Test4
} else {return}
If ($failure -eq $false) {
Test5
} else {return}
})

function Test1 {
If (Get-Process -Name chrome) {
do something
}
else {
$failure=$true
return}
}

function Test2 {
If (Get-Process -Name explorer) {
do something
}
else {
$failure=$true
return}
}

function Test3 {
If (Get-ChildItem -Name "Documents") {
do something
}
else {
$failure=$true
return}
}

function Test4 {
If (Get-ChildItem -Name "Desktop") {
do something
}
else {$failure=$true
return}
}

function Test5 {
If (Get-LocalUser -Name administrator){
do something
}
else {
$failure=$true
return}
}

Is there a shorter or better way to do this?

March 4, 2018 at 8:53 am

Hard exit as you are doing, are closing the session thus effectively crippling the form.
The workarounds you are mentioning are prudent.