2012-04-10 2 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

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을 참조하십시오.

관련 문제