user337598
user337598

Reputation:

Test for function empty return value

(edit) an empty function does in fact return a null, something led me astray, leaving the question here as a reminder...

Where $null does not cut it. My scenario is simplest explained as a snippet, I have a function someone wrote

function PositiveInt([string]$value) { 
    if ([int]($value) -ge 0) {[int]$value}
}

Which returns nothing in the negative case or throws if the input is not a numeric string. How can I test for the return in the negative case? I tried this

if ($null -eq (PositiveInt -1)) {
    write-host "not positive :)"
}

But it obviously won't work, because no return value is not equal to $null . How can I test if a function or expression simply does not return anything at all? Don't try fix my contrived function, its the absence of "$empty" (sic) I want to do a test for, but cannot because powershell binding does not mandate that a function or even an expression actually returns anything at all?

# hacky unclear solution proposed
$temp = @(PositiveInt -1)
if ($temp.length -eq 0) {
    write-host "not positive :)"
}

I drew some inspiration from this In Powershell what is the idiomatic way of converting a string to an int? posting. but I'm asking a different question I believe. Aside from the casting to array workaround, is there a cleaner way?

(edit) Have to admit something environmental or in the actual code context was at play, in PS 5.1 a function call returns $null as @AnsgarWiechers pointed out.

Upvotes: 2

Views: 3982

Answers (3)

Emperor XLII
Emperor XLII

Reputation: 13442

You could use the -is or -isnot type operators to check if the result successfully converted to an integer:

if( (PositiveInt '-1') -isnot [int] ) {
  write-host 'negative'
}

Upvotes: 2

Micky Balladelli
Micky Balladelli

Reputation: 10001

You could try the following:

if ((PositiveInt -1) -eq $null) {
    write-host "not positive :)"
}

Upvotes: 1

CB.
CB.

Reputation: 60938

do you like this?

if ( [string]::IsNullOrEmpty( (PositiveInt -1) ) ) {
    write-host "not positive :)"
}

Upvotes: 0

Related Questions