Returning multiple values in a powershell function is something that took me an embarrassing amount of time to figure out. Its not documented all that well and there are very few blog posts on the topic. It turns out there are a few ways to do this but I keep falling back to using hashtables, they are the most dynamic and pretty much anything can be returned with almost no issues. Below is a very simple example of how to make this work.
- Create a hashtable with: “[hastable]$varname = @{}”.
- Then do all of the work you need done and save your results in a property that you would like.
- Return the parent variable name and then you are able to access it via the properties you made.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Function DoThings ($things, $stuff) { [hashtable]$return = @{} if ($things -eq $stuff) { $status = 0 $msg = "Success" } else { $status = 1 $msg = "Failed" } $return.status = $status $return.msg = $msg return $return } $result = DoThings $things $stuff $result.msg $result.status |
Hope this helps!