1

Consider:

function func {
    echo ALERT
    return $false
}

if (func) {
    Write-Output "TRUE"
}

This code writes TRUE despite the function returning false. However, when I write [void]echo ALERT, PowerShell throws an error:

Unexpected token 'echo' in expression or statement.

How do I fix this code?

1 Answer 1

1

echo ALERT in your code returns a string (echo is an alias for Write-Output).

If you make an if check on a string, PowerShell checks if the string is not null or empty.

Therefore it always returns true.

If you want to alert the user of the "ALERT", use Write-Host.

function func {
    Write-Host ALERT
    return $false
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why I can't simply write [void]echo (it throws error)? I had to wrap echo in {} i. e. [void]{echo ALERT} to make code pass syntax check.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.