Tuesday, March 18, 2014

PowerShell: How to return multiple values from a Function?

If you like to return multiple values from a function, simply populate a hash table variable in function and return the variable. See my example below. Feel free to use my example function and Enjoy.

 

Function Get-UserInfo($username)
{
    #Create an hashtable variable
    [hashtable]$Return = @{}
   
    Import-Module ActiveDirectory
   
    $ADUser = Get-ADUser -Identity $username -Properties Department, employeeNumber,l,Manager
   
    #Assign all return values in to hashtable
    $Return.Name = $ADUser.name
    $Return.EmployeeNo = $ADUser.employeeNumber
    $Return.Location = $ADUser.l
    $Return.Department = $ADUser.department
    $Return.Manager = ( Get-ADUser $ADUser.manager ).Name
   
    #Return the hashtable
    Return $Return
}

# Example usable of the Get-UserInfo function
# to show how to return multiple values

$User = Get-UserInfo("JohnDoe")

"Name: " +$User.Name
"Manager: " +$User.Manager
"Location: " + $User.Location
"Department: " + $User.Department
"Employee Number: " + $User.EmployeeNo

1 comment:

  1. Time is more valuable than money, because time is irreplaceable. See the link below for more info.


    #Irreplaceable
    www.ufgop.org

    ReplyDelete

Followers

hit counter