Referring to variables created in a function

Welcome Forums General PowerShell Q&A Referring to variables created in a function

Viewing 2 reply threads
  • Author
    • #235828
      Topics: 3
      Replies: 4
      Points: 37
      Rank: Member


      Trying to grasp the idea of variable scopes. I know a variable only exists inside a function and you would need to add $script:variablename to get the variable to be seen outside the function. So, from within the function and outside the function when I need the variable value do I always need to use $script:variablename or just $variablename?




    • #235843
      Topics: 5
      Replies: 2384
      Points: 6,066
      Helping Hand
      Rank: Community MVP

      Even if it’s possible it’s highly recommended not to use variables from another scope. But yes – if you specify a variable as for example GLOBAL you could access it from another scope without the scope modifier.

    • #235852
      Topics: 12
      Replies: 1652
      Points: 2,707
      Helping Hand
      Rank: Community Hero

      It’s better to provide a specific example on what you are trying to accomplish. Generally, you should not reference a global\script var like this:

      #Bad, refrencing variables into a function
      function Test-It {
          'Processing {0}' -f $Global:SomeVar
      $Global:SomeVar = 'Some Value'

      A better approach is to create a param:

      #Good, create a param and pass it to the function
      function Test-It {
          param (
          'Processing {0}' -f $SomeVar
      $SomeVar = 'Some Value'
      Test-It -SomeVar $SomeVar
Viewing 2 reply threads
  • You must be logged in to reply to this topic.