Michael Frederick
Michael Frederick

Reputation: 327

Another PowerShell return issue

I've read some of the postings about Powershell and the return statement, but this script seems pretty straightforward to me:

function test ($n) {
    if($n -lt 0) {
        return "negative"
    }
    return "positive"
}

But when I execute it:

PS C:\Users\spadmin> test 5
positive
PS C:\Users\spadmin> test -3
positive

this output makes no sense. In an effort to try and be even more clear, I changed the function to:

function test1 ($n) {
    if($n -lt 0) {
        return "negative"
    } else {
        return "positive"
    }
}

and I get the same results. How do I get the function to return only the string "negative" for input values less than zero and "positive" from input values greater than or equal to zero?

Upvotes: 1

Views: 146

Answers (2)

notjustme
notjustme

Reputation: 2494

Try this;

function test ([int]$n) {
    if($n -lt 0) {
        return "negative"
    }
    return "positive"
}

Upvotes: 3

Bill_Stewart
Bill_Stewart

Reputation: 24585

Use a typed parameter:

function test([Int] $n) {
...

Upvotes: 1

Related Questions