1

I have a script that contains a function that defines some variables within it for use later. For example, it looks like this:

$Rig = "TestRig1"

    Function Setup{
       If ($Rig -eq "TestRig1") {
           $Script:Server="Alpharius"
           $Script:IIS1="Tactical"
           $Script:IIS2="Assault"
       }
    }

Setup
<do things with $Server>

(that's not the actual script, but it's similar)

What I'm curious about is if there's a better way to note this rather than individually labeling each variable with their scope. Is there some way I can state that all variables declared within a function are to be Script-scope?

1 Answer 1

5

One option is to run the function in the local scope by dot-sourcing it:

$Rig = "TestRig1"

    Function Setup{
       If ($Rig -eq "TestRig1") {
           $Server="Alpharius"
           $IIS1="Tactical"
           $IIS2="Assault"
       }
    }

. Setup
<do things with $Server>

Note the dot and space before 'Setup' - the space has to be there. This will run the function in the current scope, and create the variables there. Just be sure they won't conflict with any existing variable names already in the scope.

another option is to use a hash table:

$Rig = "TestRig1"

$RigParams = @{}

    Function Setup{
       If ($Rig -eq "TestRig1") {
           $RigParams.Server="Alpharius"
           $RigParams.IIS1="Tactical"
           $RigParams.IIS2="Assault"
       }
    }

Setup
<do things with $RigParams.Server>

The function will update the hash table keys in the parent scope instead of creating new variables in the function scope.

Sign up to request clarification or add additional context in comments.

3 Comments

I tested out both of your solutions, and I couldn't get the hash table to work (when I tried to write-host $RigParams.IIS1 it displayed nothing) but calling the function in the local scope worked just fine. I'll do some more reading on hash table variables, I'm wondering if I'm not populating them correctly.
Make sure you used the right syntax for Write-Host - "$($RigParams.IIS1)"
Ah, that would be it. 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.