Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

powershell - Boolean variable gets returned as an Object[]

I have a function which is returning a boolean variable

function test ($param1, $param2)
{
  [boolean]$match=$false;

  <# function logic #>

  return $match
}

when I try and catch the function call in a variable $retByFunct=testing $param1 $param 2

I am getting $retByFunct as an Object Array. If I try and force the $retByFunct to be a boolean variable i.e. [boolean] $retByFunct=testing $param1 $param 2, I get the following error.

Cannot convert value "System.Object[]" to type System.Boolean

I checked out $match.GetType() just before returning it. The console says its a boolean, so am confused as to why after function call its getting converted to an Object Array.

I am aware this happens for some collection objects and there is a work around for that, but how do I handle a case for a variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As @mjolinor said, you need to show the rest of your code. I suspect it's generating output on the success output stream somewhere. PowerShell functions return all output on that stream, not just the argument of the return keyword. From the documentation:

In PowerShell, the results of each statement are returned as output, even without a statement that contains the Return keyword. Languages like C or C# return only the value or values that are specified by the return keyword.

There's no difference between

function Foo {
  'foo'
}

or

function Foo {
  'foo'
  return
}

or

function Foo {
  return 'foo'
}

Each of the above functions returns the string foo when called.

Additional output causes the returned value to be an array, e.g.:

function Foo {
  $v = 'bar'
  Write-Output 'foo'
  return $v
}

This function returns an array 'foo', 'bar'.

You can suppress undesired output by redirecting it to $null:

function Foo {
  $v = 'bar'
  Write-Output 'foo' | Out-Null
  Write-Output 'foo' >$null
  return $v
}

or by capturing it in a variable:

function Foo {
  $v = 'bar'
  $captured = Write-Output 'foo'
  return $v
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...