0

I have a script like so:

test.ps1

param (
    $name,
$age
)

function load-parameters()
{
$name = "Bob"
$age = "23"

Write-Host "name: " $name
Write-Host "age: " $age
}

load-parameters
Write-Host "name: " $name
Write-Host "age: " $age

Except instead of name and age, i have about 10 parameters that i'm loading and initializing inside load-parameters.

The problem I am trying to solve is trying to preserve the values of the initialization of (what i think are) global scope functions inside the script.

The function above returns:

name:  Bob
age:  23
name:
age:

Are the local edits hardwired when you change them into functions? it looks like the implementation is that parameters are being passed by copy to functions you write inside a script.

I realize I can get around this by passing the variables by reference (if there is even a thing in powershell functions), but that would be ugly given the number of parameters i need to pass. is there a way to specify the scope of the variable when i'm doing the assignment inside function "load-parameters"?

1 Answer 1

1

It is not super clear what you want to achieve with the load parameters. What you are trying to do maybe solved with default values for the parameters for your script:

param (
    $name = "Bob",
    $age = "23"
)

Another option for what you are trying is to use the variables with script scope:

$script:name = "Bob"

So in the functions you can do something like:

function load-parameters
{
$script:name = "Bob"
$script:age = "23"

Write-Host "name: " $name
Write-Host "age: " $age
}
Sign up to request clarification or add additional context in comments.

1 Comment

can't use default values as my loading logic is a giant switch statement, so there's conditional logic there that i want to keep in load-parameters(), but the script scope worked great. thanks.

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.