在PowerShell模块中设置属性

Ste*_*ans 7 powershell powershell-2.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
Run Code Online (Sandbox Code Playgroud)

从PS命令行:

Import-Module Test
Set-Property "New Value"
Get-Property
Run Code Online (Sandbox Code Playgroud)

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

And*_*ykh 12

杰米是对的.在您的示例中,在第一行中,$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
Run Code Online (Sandbox Code Playgroud)

按照Jamey的例子,它会起作用.请注意,您不必在第一行中使用范围限定符,因为默认情况下您在脚本范围内.此外,您不必在Get-Property中使用范围限定符,因为默认情况下将返回父范围变量.