1

I'm trying to create an if and else statement within PowerShell that exits my code if the $value variable has a 0 or 1.

The below is my code which is executed remotely:

$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"
        }
    }

}

$value = invoke-ascurrentuser -scriptblock $MsgBox -CaptureOutput

$exit = "0"

Write-Host $value

if ($value.Equals($exit)){
    Write-Host "Script Exiting"
    exit
}
else{
    Write-Host "Continuing Script"
}

Am I comparing the wrong way in PowerShell?

I tested the code with Write-Host and my scriptblock returns 0 or 1 as planned.

When it gets to the If and Else statement it doesn't seem to compare value and exit, and will instead go straight to the else statement and Write "Continuing Script"

I've also tried with $value -eq 0 and $value -eq "0".

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Exit should be a number, not a string : $exit = "0" – jdweng Jan 30 '23 at 17:19
  • `"0"` and `"1"` are _output values_ here - not _exit codes_ set with `exit` (the name of the variable notwithstanding). While you could argue that `return 1` and `return 0` would be better in general, on the _caller_ side all output turns into _strings_ anyway in this case, due to use of `Invoke-AsCurrentUser -CaptureOutput`. To put it differently: your comment is a distraction. (As an inconsequential aside: if you try something like `exit "1"`, PowerShell automatically converts the string to a number, if possible, and falls back to `0`) – mklement0 Jan 30 '23 at 18:16

1 Answers1

0

Invoke-AsCurrentUser, from the third-party RunAsUser module, when used with -CaptureOutput invariably outputs text, as it would appear in the console, given that a call to the PowerShell CLI, is performed behind the scenes (powershell.exe, by default).

The captured text includes a trailing newline; to trim (remove) it, call .TrimEnd() before comparing values:

# .TrimEnd() removes the trailing newline.
$value = (Invoke-AsCurrentuser -scriptblock $MsgBox -CaptureOutput).TrimEnd()

if ($value -eq '0') {
    Write-Host "Script Exiting"
    exit
}
else {
    Write-Host "Continuing Script"
}
mklement0
  • 382,024
  • 64
  • 607
  • 775