Home > OS >  Comparing a String Variable via PowerShell
Comparing a String Variable via PowerShell

Time:01-31

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".

CodePudding user response:

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"
}
  • Related