sourcecode

Powershell 스크립트에서 반환 값을 잡는 방법

codebag 2023. 11. 4. 10:39
반응형

Powershell 스크립트에서 반환 값을 잡는 방법

반환 값이 있는 다른 파워셸 스크립트를 실행하는 파워셸 스크립트(.ps1)가 있습니다.

다음 명령을 사용하여 스크립트를 호출합니다.

$result = Invoke-Expression -Command ".\check.ps1 $fileCommon"

Write-Output $result

출력은 단지Write-Ouput다른 스크립트를 가지고 있지만 반환 값은 가지고 있지 않습니다.$true아니면$false.

다른 대본에서 돌아오는 것을 어떻게 잡을 수 있습니까?

뒤에 있는 표현은returnPowerShell의 statement는 다른 모든 식과 마찬가지로 평가됩니다.출력이 발생하면 stdout으로 적습니다.$ 결과는 스크립트에 의해 stdout으로 작성된 것을 모두 받습니다.stdout에 둘 이상의 것이 쓰여지면, 이런 것들이 배열됩니다.

예를 들어 check.ps1의 경우 다음과 같습니다.

Write-Output "$args[0]"
return $false

그리고 당신은 그것을.

$result = &".\check.ps1" xxx

그리고나서$result값 "xxx"( 문자열) 및 "False"(boole)가 있는 크기 2의 객체 배열이 됩니다.

반환 값만 stdout(가장 깨끗한 방법)에 쓰도록 스크립트를 변경할 수 없는 경우 마지막 값을 제외한 모든 것을 무시할 수 있습니다.

$result = &".\check.ps1" xxx | select -Last 1

지금이다$result부울 값으로 "False"만 포함됩니다.

스크립트를 변경할 수 있는 경우, 변수 이름을 전달하여 스크립트에 설정하는 것도 방법입니다.

통화:

&".\check.ps1" $fileCommon "result"
if ($result) {
    # Do things
}

스크립트:

param($file,$parentvariable)
# Do things
Set-Variable -Name $parentvariable -Value $false -Scope 1

-Scope 1는 상위(caller) 범위를 나타내므로 호출 코드에서 읽기만 하면 됩니다.

스크립트 함수에서 값을 반환하는 확실한 방법은 변수를 설정하는 것입니다.출력 위치에 의존하는 것은 예를 들어 누군가가 스트림에 새로운 출력을 추가하는 경우 미래에 손상될 가능성이 있습니다. Write-Output/Write-Warning/Write-Verbose 등...

리턴은 다른 언어와 달리 스크립트 기능에서 너무 오해의 소지가 있습니다.파워셸에서 클래스+기능을 사용하는 또 다른 메커니즘을 보았지만, 당신이 찾고 있는 것이 아닌지 의심됩니다.

function Test-Result{
            Param(
                $ResultVariableName
            )
 try{
     Write-Verbose "Returning value"
     Set-Variable -Name $ResultVariableName -Value $false -Scope 1
     Write-Verbose "Returned value"
     return $value # Will not be the last output
    }
    catch{
     Write-Error "Some Error"
    }
    finally{
     Write-Output "finalizing"
     Write-Verbose "really finalizing"
    }

#Try these cases 

$VerbosePreference=Continue

Test-Result 

$MyResultArray=Test-Result *>&1; $MyResultArray[-1] # last object in the array

Test-Result "MyResult" *>&1; $MyResult

언급URL : https://stackoverflow.com/questions/50578510/how-catch-return-value-in-a-powershell-script

반응형