TonyMcG
TonyMcG

Reputation: 13

trying to pass variables from a powershell function to another

I am trying to create 2 variables in a function and then passing them into the second function. the 2 variables just don't seem to be being passed in. I Have tried returning the variables but doesn't seem to work either. what am I missing?

enter code here

function get-PSnames 
    {
        $tony = 'tiny'
        $tlony = 'jommy' 
    }

function get-PSadded ([string] $name,[string]$name2)
    {
        $tony + $tlony   
    }

    get-PSnames
    get-PSadded "$tony, $tlony"

Upvotes: 1

Views: 762

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

Variables in PowerShell are scoped, meaning they only exist for the duration of the function that they're created in.

What you'll want to do is create a function that returns the string values:

function Get-PSNames
{
  'tiny'
  'jommy'
}

You can then assign them to your own variables when you call the function:

$tony,$tlony = Get-PSNames

And pass them as arguments to your other function:

function Get-PSAdded([string]$Name, [string]$OtherName)
{
  # Remember to use the same variable names you used when defining the function's parameters
  $Name + $OtherName
}

# call the function 
$tony,$tlony = Get-PSNames

$newName = Get-PSAdded -Name $tony -OtherName $tlony

Upvotes: 1

Related Questions