• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4137
  • Last Modified:

Return Value from Powershell Function

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
Kent Dyer
Asked:
Kent Dyer
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
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
 
Kent DyerAuthor Commented:
Way too simple..  Sheesh..

Thank you!!
0

Featured Post

Nothing ever in the clear!

This technical paper will help you implement VMware’s VM encryption as well as implement Veeam encryption which together will achieve the nothing ever in the clear goal. If a bad guy steals VMs, backups or traffic they get nothing.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now