引用同一个 PSCustomObject 的另一个属性 [英] Reference another property of the same PSCustomObject

查看:59
本文介绍了引用同一个 PSCustomObject 的另一个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我声明了一个 PSCustomObject 并且它有多个成员.其中一些需要相互引用.例如

I have a PSCustomObject declared and it has multiple members. Some of them need to reference each other. E.g.

$data = [PSCustomObject]@{
    a = "x"
    b = "y"
    c = "z"
    d = "$a - $b - $c"
}

我期望的是 $data.d 返回:

x - y - z

我尝试通过以下方式引用其他属性:

I've tried referencing the other properties by:

  • $a
  • $this.a
  • $_.a
  • $data.a

但这些似乎都不起作用,$data.d 的输出是:

But none of these seem to work and the output of $data.d is:

 -  -

注意:如果我们第二次运行脚本 $data.a 可能会引用上一次运行中的 $data 变量,所以我们需要确保在运行之前清除变量.

Note: if we run the script for the second time $data.a might reference the $data variable from the previous run, so we need to make sure that the variables are cleaned before running.

推荐答案

我问你是否真的在寻找 ScriptProperty:

I quess you actually looking for a ScriptProperty:

$data = [PSCustomObject]@{
    a = "x"
    b = "y"
    c = "z"
}

$data | Add-Member ScriptProperty d {"$($this.a) - $($this.b) - $($this.c)"}

$data

a b c d
- - - -
x y z x - y - z

这篇关于引用同一个 PSCustomObject 的另一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆