sourcecode

powershell: [ref] 변수에서 호스트 값을 쓰는 방법

copyscript 2023. 10. 1. 21:52
반응형

powershell: [ref] 변수에서 호스트 값을 쓰는 방법

저는 파워셸을 처음 접했는데 함수 내에서 [ref] 변수 값을 인쇄하는 방법을 찾고 있습니다.

테스트 코드는 다음과 같습니다.

function testref([ref]$obj1) {
  $obj1.value = $obj1.value + 5
  write-host "the new value is $obj1"
  $obj1 | get-member
}


$foo = 0
"foo starts with $foo"
testref([ref]$foo)
"foo ends with $foo"

이 테스트를 통해 얻은 결과는 다음과 같습니다.제가 바라던 $obj1의 가치를 얻지 못한다는 것을 알게 될 것입니다.저도 $obj1을 전달해 보았습니다.write-host 에 대한 호출에서 값이 발생했지만 동일한 응답을 생성했습니다.

PS > .\testref.ps1
foo starts with 0
the new value is System.Management.Automation.PSReference


   TypeName: System.Management.Automation.PSReference

Name        MemberType Definition
----        ---------- ----------
Equals      Method     bool Equals(System.Object obj)
GetHashCode Method     int GetHashCode()
GetType     Method     type GetType()
ToString    Method     string ToString()
Value       Property   System.Object Value {get;set;}
foo ends with 5

당신은 아마 다음을 시도했을 것입니다.

write-host "the new value is $obj1.value"

그리고 그에 상응하는 출력을 얻었습니다.

the new value is System.Management.Automation.PSReference.value

제 생각에 당신은 그 사실을 몰랐을 것 같습니다..value결과물의 끝에

문자열에서는 속성에 액세스하는 동안 다음과 같은 작업을 수행해야 합니다.

write-host "the new value is $($obj1.value)"

또는 다음과 같은 문자열 형식을 사용합니다.

write-host ("the new value is {0}" -f $obj1.value)

또는 값을 외부에 지정합니다.$value = $obj1.value문자열로 사용합니다.

언급URL : https://stackoverflow.com/questions/7199142/powershell-how-to-write-host-value-from-ref-variable

반응형