[SOLVED] Powershell : Function to create new-variable not working

Issue

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 ?

Solution

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.

Answered By – Mathias R. Jessen

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.