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

Advertisements

2 thoughts on “PowerShell: How to return multiple values from a Function?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s