variable scope in functions

This topic contains 2 replies, has 2 voices, and was last updated by  Shane Lindberg 2 years, 3 months ago.

  • Author
    Posts
  • #27697

    Shane Lindberg
    Participant

    I have been just learning the very basics of power shell. From what I understand variables by default are private if declared in a function. I do not understand why $private:var is needed. are the following two functions equivalent in what they do?

    function test {
        $a = 6 }
    
    function test2 {
        $Private:a = 6}
    
    
  • #27698

    Max Kozlov
    Participant

    take a look at this example:

    function test1 {
        $a = 6
    	write-host "test1: $a"
    	function inner1 {
    		write-host "inner1: $a"
    		$a=7
    	}
    	inner1
    	write-host "test1: $a"
    }
    
    function test2 {
        $Private:a = 6
    	write-host "test1: $a"
    	function inner2 {
    		write-host "inner2: $a"
    		$a=7
    	}
    	inner2
    	write-host "test2: $a"
    }
    test1
    test2
    

    inner2 doesn't print any value because test2 have private variable

  • #27748

    Shane Lindberg
    Participant

    I see functions keep stuff private from outside of them by default. To keep stuff private from functions you need the $private: syntax to accomplish this.

You must be logged in to reply to this topic.