【问题标题】:powershell: how to write-host value from [ref] variablepowershell:如何从 [ref] 变量写入主机值
【发布时间】:2011-11-04 04:13:52
【问题描述】:

我是 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 的值。我还尝试在对 write-host 的调用中传入 $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

【问题讨论】:

    标签: function powershell ref


    【解决方案1】:

    你可能会尝试过:

    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这样在外部赋值并在字符串中使用。

    【讨论】:

      猜你喜欢
      • 2021-03-02
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      相关资源
      最近更新 更多