在PowerShell模块中设置属性

时间:2012-04-10 21:34:41

标签: powershell powershell-v2.0

我有一个名为Test.psm1的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

此时我希望它返回“新值”,但它返回“默认值”。我试图找到一种方法来设置该变量的范围,但没有任何运气。

2 个答案:

答案 0 :(得分:10)

杰米是对的。在您的示例中,在第一行中,$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 :(得分: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