Solved

Return Value from Powershell Function

Posted on 2013-05-17
2
3,883 Views
Last Modified: 2013-05-17
At the risk of asking a "silly" question..  I would like to know the "best practice" for "returning" a value from a PowerShell function..  There are several different ways that this can be done..  I would like to have two different variables to be re-usable elsewhere in the script..

# http://social.technet.microsoft.com/Forums/en-US/ITCG/thread/4da65aaa-f261-4d7c-8726-d7613f56d0eb/
#[PowerShell] - Return value from a function
Function showval
{
$val="keeper"
#Return $val
$val2="forkeeps"
Return ,$val,$val2
}

$ReUse = showval
#Method 1 - ForEach
$ReUse | ForEach { `
  "Item: "+$_
  }

#Was thinking of how to implement a counter for the variable
  #Get-Content foo.txt  | foreach { '{0} {1}' -f $_.ReadCount, $_ }

#This also works..
# Foreach ($Reuses in $Reuse) { `
#  "Item: $Reuses" `
# }

#Use of split works too..
#Write-Host "ReUse "$ReUse # shows: keeper forkeeps
#$dnstream=$ReUse.Split(",")[0]
#$dnstream1=$ReUse.Split(",")[1]
#Write-Host "value1 "$dnstream # shows keeper
#Write-host "value2 "$dnstream1 # shows forkeeps

Open in new window


Thanks,

Kent
0
Comment
Question by:Kent Dyer
2 Comments
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 39176732
here's a simple example:
function returnMV()
{
$data = @()
$data += (Get-Process | select -first 1)
$data += Get-Date
$data += "jonny brown"
return $data  
}

$returnvalue = returnMV
$returnvalue[0]
$returnvalue[1]
$returnvalue[2]

Open in new window


in youe case:
Function showval
{
$data = @()
$val="keeper"
$data+=$val
#Return $val
$val2="forkeeps"
$data+=$val2
Return $data
}

Open in new window

0
 
LVL 17

Author Closing Comment

by:Kent Dyer
ID: 39176759
Way too simple..  Sheesh..

Thank you!!
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Set OWA language and time zone in Exchange for individuals, all users or per database.
This article will help you understand what HashTables are and how to use them in PowerShell.
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
The viewer will learn how to count occurrences of each item in an array.

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question