在PowerShell模块中设置属性
我有一个名为Test.psm1的PowerShell模块。我想在一个变量上设置一个值,并在调用该模块中的另一个方法时使其可访问在PowerShell模块中设置属性,powershell,powershell-2.0,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 -Funct
#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
此时,我希望它返回“新值”,但它返回“默认值”。我试图找到一种方法来设置该变量的范围,但没有任何运气。您的思路是正确的。访问$property时,需要强制模块中的方法使用相同的作用域
$script:property = 'Default Value'
function Set-Property([string]$Value) { $script:property = $value; }
function Get-Property { Write-Host $script:property }
Export-ModuleMember -Function *
有关更多信息,请参阅。杰米是正确的。在您的示例中,在第一行,
$property='Default Value'
表示一个文件范围的变量。在Set Property
函数中,赋值时,将赋值给函数外部不可见的局部作用域变量。最后,在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属性中使用scope限定符,因为默认情况下将返回父scope变量。+1模块有自己的作用域,用于将模块与从调用方环境中拾取的意外污染隔离开来。