Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell : Function to create new-variable not working

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading