簡體   English   中英

powershell:如何從[ref]變量寫入主機值

[英]powershell: how to write-host value from [ref] variable

我是Powershell的新手,我正在嘗試研究如何在函數中打印[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.value但是生成了相同的響應。

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之外指定值,並在字符串中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM