4

I'm trying to make a simple function to create Variables in powershell with generated name

I'm using this code :

    function createAnewVariable {
 [CmdletBinding()]
    Param(
          [String]$Name
    )
    New-Variable -Name GenLink$Name -Value "AMIGA" -Option AllScope
}

createAnewVariable -Name "AutoVAR"

Outside a function it's working perfectly when i do a get-variable i can see my automatic created variables like $GenLinkName but inside a function i don't have access to the varaible in the list and i can't call it ! oO

It's maybe simple but i don't understand why :)

Someone can tell me where i'm wrong please ?

1 Answer 1

5

Variables in PowerShell are scoped, and defaults to the current local scope, ie. the function body. The AllScope option does not make it available to antecedent scopes, it simply ensures PowerShell copies the variable into any new child scope created from the current scope.

To make the variable available in the parent scope, use -Scope 1 when calling New-Variable:

function createAnewVariable {
    [CmdletBinding()]
    Param(
        [String]$Name
    )
    
    New-Variable -Name "GenLink$Name" -Value "AMIGA" -Scope 1
}

createAnewVariable -Name "AutoVAR"

# This is now available in the calling scope
$GenLinkAutoVAR

Be aware that if the function is module-scoped (eg. the function is part of a module), the parent scope will be the module scope, meaning all other functions in the same module will be able to see it too.

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

1 Comment

From module scope one can use $PSCmdlet.SessionState.PSVariable.Set() to set a variable in the caller's scope.

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.