1

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"
1
  • Call the function inside your Get-PSNames function, unless you want to make your variables global: Get-PSNames -Name $tony -Name2 $tlony, functions run in it's own scope and not the global scope not making your variables available to anything else but, that function unless specified using a global variable: $Global:myvariable. Also, parameters are passed individually and not as a whole. Currently, you're passing $tony + $tlony as a whole instead of individual values. Commented Sep 3, 2021 at 12:13

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for that, would never of got there.
@TonyMcG You're welcome! If my answer solves you problem, consider marking it "accepted" by clicking the checkmark outline on the left :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.