2

I'm writing a PowerShell function, and I want it to return a single Boolean. The problem is that PowerShell will return anything in the pipeline and not just what was explicitly included in the return statement.

Consider the following code.

function getTrue(){
  $testVariable = "test"
  $test
  return $true
}

$answer = getTrue

Write-host $answer

The output of this code is

test True

This returns a System.Object[]. I want to force the return value to be a System.Boolean.

This code works fine if I add a Write-Host:

function getTrue(){
  $testVariable = "test"
  Write-Host $test
  return $true
}

The only problem is that I'm depending on a function that someone else is writing (I can't modify it), and I can't gaurantee that they used a Write-Host instead of just leaving the variable on the line by itself.

Is there a way to force the function to only return the value that I want?

1 Answer 1

8

Just use Out-Null to suppress unexpected returning:

function getTrue(){
    $test = "test";
    $test | Out-Null;
    return $true;
}

$answer = getTrue
Write-Host $answer

and

function getTrue(){
    $test = "test";
    Write-Host $test | Out-Null;
    return $true;
}

$answer = getTrue
Write-Host $answer
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.