Strange behavior with Powershell scriptblock variable scope and modules, any suggestions?

后端 未结 3 549
我在风中等你
我在风中等你 2020-12-09 04:47

NOTE: I\'m using PowerShell 2.0 on Windows Vista.

I\'m trying to add support for specifying build arguments to psake, but I\'ve run into some strange PowerShell var

3条回答
  •  感动是毒
    2020-12-09 05:17

    It appears that the $message in the scriptblock passed in is tied to the global scope e.g.:

    function Test { 
        param( 
            [Parameter(Position=0,Mandatory=0)] 
            [scriptblock]$properties = {} 
        ) 
    
        $defaults = {$message = "Hello, world!"} 
    
        Write-Host "Before running defaults, message is: $message" 
    
        . $defaults 
    
        #At this point, $message is correctly set to "Hellow, world!" 
        Write-Host "Aftering running defaults, message is: $message" 
    
        . $properties 
    
        #At this point, I would expect $message to be set to whatever is passed in, 
        #which in this case is "Hello from poperties!", but it isn't.   
        Write-Host "Aftering running properties, message is: $message" 
    
        # This works. Hmmm
        Write-Host "Aftering running properties, message is: $global:message" 
    } 
    
    Export-ModuleMember -Function "Test" 
    

    Outputs:

    Before running defaults, message is: 
    Aftering running defaults, message is: Hello, world!
    Executing properties, message is 
    Aftering running properties, message is: Hello, world!
    Aftering running properties, message is: Hello from properties!
    

    This would appear to be a bug. I'll prod the PowerShell MVP list to see if I can confirm this.

提交回复
热议问题