Wednesday, August 26, 2009

How to return multiple values from Powershell function

I used this trick few times when I had function that had to return more values…

As I wrote here, you can access dictionary object using syntax $Dictionary.Key… If your function returns dictionary, then you can use it to your advantage :)

   1: Function Get-MultiValue () { 



   2:  [hashtable]$Return = @{} 



   3:  



   4:  $Return.Success = $True 



   5:  $Return.PercentComplete = 100 



   6:  $Return.ReturnTime = $(Get-Date) 



   7:  $Return.Username = "Martin Zugec" 



   8:  



   9:  Return $Return 



  10: }




Usage is pretty obvious:





   1: $Var = Get-MultiValue 



   2:  



   3: If ($Var.Success) { 



   4:     $Var.UserName 



   5:     $Var.ReturnTime 



   6: }




Easy and useful sometimes…

5 comments:

Rei said...

Very helpfull, thanks !!!

Anonymous said...

Thanks for this post, I liked this trick

Anonymous said...

Thanks for the post, I liked this trick

Anonymous said...

THANK YOU SO MUCH!!!!!

Anonymous said...

Thank You Martin. Just used this technique to return multiple values from a function, and it worked great !

-Mario