3

I have the following snippet of PowerShell:

$property = @{
    Getter = { 80 };
}

$value = $property.Getter.Invoke() 
$value.GetType() # Shows Name = Collection'1 instead of int

I would expect $value.GetType() to return Int32 but instead it returns a collection.

I can't just take element [0] because sometimes the Getter function will return an array.

How can I fix this?

2
  • 2
    Standard tricks for preventing unrolling apply: (,$value)[0] will give you the first element of the returned collection (and it always returns a collection, because that's the signature of ScriptBlock.Invoke()) without eagerly unrolling it if it's enumerable. Commented Oct 20, 2021 at 10:15
  • Does this answer your question? Why does invoking a Powershell script block with .Invoke() return a collection?: $property.Getter.InvokeReturnAsIs().GetType() Commented Oct 20, 2021 at 10:18

1 Answer 1

5

You can strictly declare the type of the return value by this way. For example, the return type will be Double :

cls
$property = @{
    Getter = [Func[Double]]{ 80 }
}

$value = $property.Getter.Invoke() 
$value.GetType().Name
# Double
Sign up to request clarification or add additional context in comments.

4 Comments

To be precise, this doesn't declare a return type as such, it instead makes Getter a Func<double> instead of a ScriptBlock, and thus uses a very different Invoke method. This becomes relevant if you wanted to do something else with Getter than invoking it (like retrieving the AST).
btw, you could also simply use the unary comma operator: $property = @{ Getter = ,{ 80 } }
@JeroenMostert , @JeroenMostert , Func<TResult> TResult:The type of the return value. learn.microsoft.com/en-us/dotnet/api/…
Yes, of course the generic parameter is the return type of the Func assigned to Getter, but this is not the same as declaring the type of the value returned by the script block (e.g. Getter = { [double] 80 }, which of course does not resolve the issue because it's still a ScriptBlock)). It is important to note that these things are very different semantically, they just happen to both have Invoke methods -- $property.Getter.GetType() is different in both cases. Note that you can also declare it as Func[Object] or even Func[bool] -- PowerShell doesn't object to casting.

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.