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
    Posts
    • #235828
      Participant
      Topics: 3
      Replies: 4
      Points: 37
      Rank: Member

      Hi-

      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?

       

      Ty.

       

    • #235843
      Participant
      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
      Participant
      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'
      Test-It
      

      A better approach is to create a param:

      #Good, create a param and pass it to the function
      function Test-It {
          param (
              $SomeVar
          )
      
          '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.