Daniel Glos
Daniel Glos

Reputation: 87

Powershell: message-box crashes do while loop

I have this simple script that just gets path an verifies if it exists.

function getPaths(){

        $pathFromCMS = Read-Host "Please set the path for the copy files"
        $pathToCMS = Read-Host "Please set the path to your CMS application"

        if ((Test-Path -Path $pathFromCMS ) -and (Test-Path -Path $pathToCMS )){
            Return $True
        }
        else{
            [System.Windows.MessageBox]::Show('You have provided wrong path!')
            Return $False
        }
}
do{}while (! (getPaths) -eq $True)

echo "Hello there"

The problem is with the MessageBox::Show function. It somehow makes the loop stop when entering wrong paths. When I change it just for Write-Host "You have provided wrong path!" everything works fine. Can someone explain why this happens pls ?

Upvotes: 0

Views: 455

Answers (3)

Janne Tuukkanen
Janne Tuukkanen

Reputation: 1660

The [System.Windows.MessageBox]::Show method returns a value, and that breaks your loop condition. You can suppress the return value by piping to Out-Null:

[System.Windows.MessageBox]::Show('You have provided wrong path!') | Out-Null

Upvotes: 3

boxdog
boxdog

Reputation: 8432

A MessageBox can have different buttons on it (e.g. YES/NO) and so is shown synchronously to allow you to capture what the user clicks. For example:

$preference = [System.Windows.MessageBox]::Show('Do you like MessageBoxes?', "MessageBox Preference", [System.Windows.MessageBoxButton]::YesNo)

In your case, even if you only want 'OK', it is still a good idea for it to wait, since the user always needs to manually dismiss it, unlike the output from Write-Host.

Upvotes: 0

Traveling Man
Traveling Man

Reputation: 105

It is because there is nothing in your do{} block to be executed while the condition is satisfied.

What you want is:

do{(getPaths)}while ((getPaths) -ne $True)

Upvotes: -1

Related Questions