Function static variables

This topic contains 0 replies, has 1 voice, and was last updated by  Forums Archives 5 years, 9 months ago.

  • Author
    Posts
  • #5813

    by gbritton at 2013-04-17 07:02:05

    Does PowerShell have support for function-scope static variables? e.g. something like:

    function foo {
    #declare a static variable
    $bar
    }

    The idea is that the static variable is:

    1. only visible from within function foo (so, not from the parent scope and not in any child scope)
    2. is persistent between calls, so I can set $bar to some value and have that value be there for any subsequent call to foo unless I change it (and then only from with function foo)

    I had thought of using $script:bar but that seems to be too broad. That is, it is available anywhere in the script that has that function, which is not what I want. I may have another function — foobar — that also wants a static variable $bar but that has to be a different one.

    e.g. these two functions reference the same variable:


    function foo{
    " function foo, bar= $script:bar"
    $script:bar = 'foo'
    $script:bar
    }

    function bar{
    " function bar, bar= $script:bar"
    $script:bar = 'bar'
    $script:bar
    }

    Invoking them shows this:


    foo
    bar

    produces:


    function foo, bar=
    foo
    function bar, bar= foo
    bar

    What I want would produce:


    function foo, bar=
    foo
    function bar, bar=
    bar

    by ArtB0514 at 2013-04-17 07:13:43

    By default, variables defined within a function are local.
    function foo{
    Param (
    $foo = "foo",
    $bar
    )
    " function foo, bar= $bar"
    }

    function bar{
    Param (
    $bar = "bar",
    $foo
    )
    " function bar, bar= $bar"
    }

    by gbritton at 2013-04-17 07:26:23

    Agreed, however they are not static. That is, they do not retain their values between successive calls to the function. I'm looking for static variables.

    by poshoholic at 2013-04-17 07:42:31

    PowerShell does not support static variables. You'll need to find another way to accomplish what you are after. Serializing the data you want to retain to clixml files on disk using Import-Clixml/Export-Clixml is one possibility.

    by gbritton at 2013-04-17 08:08:02

    I think I found another way. I put my function in a module, declare the variables as $script, but only export the function name. It seems to work as desired.

    by poshoholic at 2013-04-17 08:26:02

    Yes, modules have their own scope so that's a good solution for maintaining state while the module is loaded.

You must be logged in to reply to this topic.