2012-04-10 65 views
4

我有一个名为Test.psm1的PowerShell模块。我想为变量设置一个值,并且在我调用该模块中的另一个方法时可以访问它。在PowerShell模块中设置属性

#Test.psm1 
$property = 'Default Value' 

function Set-Property([string]$Value) 
{ 
    $property = $Value 
} 

function Get-Property 
{ 
    Write-Host $property 
} 

Export-ModuleMember -Function Set-Property 
Export-ModuleMember -Function Get-Property 

从PS命令行:

Import-Module Test 
Set-Property "New Value" 
Get-Property 

在这一点上我想它返回“新价值”,但它的返回“默认值”。我试图找到一种方法来设置该变量的范围,但没有任何运气。

回答

9

Jamey是正确的。在您的示例中,在第一行中,$property = 'Default Value'表示文件范围变量。在Set-Property函数中,当您分配时,您将分配给在函数外部不可见的localy范围变量。最后,在Get-Property中,由于没有具有相同名称的本地范围变量,因此读取了父范围变量。如果你改变你的模块

#Test.psm1 
$property = 'Default Value' 

function Set-Property([string]$Value) 
{ 
     $script:property = $Value 
} 

function Get-Property 
{ 
     Write-Host $property 
} 

Export-ModuleMember -Function Set-Property 
Export-ModuleMember -Function Get-Property 

根据Jamey的例子,它会工作。但请注意,您不必在第一行中使用范围限定符,因为您在默认情况下处于脚本范围内。此外,您不必在Get-Property中使用范围限定符,因为默认情况下会返回父范围变量。

+1

+1模块有其自己的范围,可以将模块与来自呼叫者环境的意外污染隔离开来。 – JPBlanc 2012-04-11 04:12:54

3

你在正确的轨道上。访问$ property时,您需要强制模块中的方法使用相同的范围。

$script:property = 'Default Value' 
function Set-Property([string]$Value) { $script:property = $value; } 
function Get-Property { Write-Host $script:property } 
Export-ModuleMember -Function * 

请参阅about_Scopes了解更多信息。