programing

함수의 PowerShell 변수 증가

codeshow 2023. 8. 15. 11:50
반응형

함수의 PowerShell 변수 증가

PowerShell 함수에서 변수를 증가시키려면 어떻게 해야 합니까?

함수에 입력할 데이터 없이 아래 예시를 사용하고 있습니다.함수를 호출할 때마다 변수를 증분하려고 합니다.$increment 변수에는 1이 추가된 다음 스크립트가 완료되면 총 $increment가 표시됩니다.

아래를 실행했을 때의 총합은 0인 반면, 함수 비교는 4번 실행했고 $increment는 1번씩 증가했기 때문에 제가 원하는 결과는 4입니다.

 $incre = 0

 function comparethis() {
     # Do this comparison

    $incre++
    Write-Host $incre
 }

 comparethis #compare 2 variables
 comparethis #compare 2 variables
 comparethis #compare 2 variables
 comparethis #compare 2 variables

 Write-Host "This is the total $incre"

동적 범위 지정 문제가 발생했습니다._scopes 정보를 참조하십시오.$incret 함수 내부에는 정의되지 않으므로 글로벌 범위에서 복사됩니다.전역 $increment는 수정되지 않습니다.수정을 원하는 경우 다음을 수행할 수 있습니다.

$incre = 0

function comparethis() {
    #Do this comparison

    $global:incre++
    Write-Host $global:incre
}

comparethis #compare 2 variables
comparethis #compare 2 variables
comparethis #compare 2 variables
comparethis #compare 2 variables

Write-Host "This is the total $incre"

동일한 스크립트를 실행할 때마다 카운터를 재설정하려면$script범위:

$counter = 1;

function Next() {
    Write-Host $script:counter

    $script:counter++
}

Next # 1
Next # 2
Next # 3

와 함께$global얻을 수 있는 범위4 5 6두 번째 스크립트 실행 시, 그렇지 않습니다.1 2 3.

글로벌 변수를 사용하는 대신 변수를 참조하여 함수를 호출하는 것이 좋습니다.

[int]$incre = 0

function comparethis([ref]$incre) {
    $incre.value++;
}

comparethis([ref]$incre) #compare 2 variables
Write-Host $incre
comparethis([ref]$incre) #compare 2 variables
Write-Host $incre

언급URL : https://stackoverflow.com/questions/24645113/increment-a-variable-in-powershell-in-functions

반응형