Forum Discussion

tsmith92765's avatar
tsmith92765
Copper Contributor
Jan 24, 2023
Solved

Trying to get a ScriptBlock to End the whole script from running? Is there a way to do this?

Hello PS Community, I'm trying to utilize the below ScriptBlock for my msgBox. I created a Switch if Cancel is clicked it will exit the ScriptBlock but I want it to exit the whole Script, is there a...
  • tsmith92765's avatar
    tsmith92765
    Feb 01, 2023

    Hi Vinod_5,

    Close I was trying to get the script block of the msgbox to run and upon clicking cancel or "x" the script would exit completely.

    So I recreated the above Script block for MsgBox to return a value to the $value variable, upon returning to the main function an if statement would check $value for a 0, and if it has a 0, it will exit the script

    My Code:
    # MsgBox ScriptBlock #
    $MsgBox = {
    Add-Type -AssemblyName PresentationFramework
    $ButtonType = [System.Windows.MessageBoxButton]::OKCancel
    $MesssageIcon = [System.Windows.MessageBoxImage]::Warning
    $MessageBody = "Please save anything open in your current Web Browser, this includes Google Chrome, Microsoft Edge, and Mozilla FireFox and close each one respectively. Click Ok when done saving and closing browsers. IT Will be deleting your Cache and Cookies.

    -IT"
    $MessageTitle = "Read Me"
    $Result = [System.Windows.MessageBox]::Show($MessageBody, $MessageTitle,$ButtonType,$MesssageIcon)



    Switch ($Result){
    'Ok' {
    Return "1"
    }
    'Cancel' {
    Return "0"
    }
    }

    }

    # Invoke MsgBox as CurrentUser. #
    $value = (invoke-ascurrentuser -scriptblock $MsgBox -CaptureOutput).TrimEnd()

    if($value -eq '0'){
    Write-Host "Script Exiting"
    Write-Output "Script Exiting" >> C:\Users\$user\AppData\Local\Temp\Cookie_Cache.log
    Exit
    }

     

    Thank you for the suggestion Vinod!

Resources