powershell - 通过符号名称(键)访问脚本的多个输出

标签 powershell hashtable key-value pscustomobject

我是 powershell 脚本编写的初学者,我希望能够区分脚本的输出。让我们以这个脚本 test.ps1 为例:

param([System.String] $w)
$x=$w+" is correct"
$y=$w+ " is false"
$x
$y

要执行它并检索值 $x 和 $y,我正在这样做:

$a=.\test1.ps1 -w test
$a[0] #this is x
$a[1] # this is y

有没有一种方法可以使用类似于 $a.x 的东西来检索 $x 值?

谢谢。

最佳答案

要执行您想要的操作,您将需要一个包含键/值对或命名属性的对象。例如,您可以创建一个名为 a 的对象,其属性为 xy:

$x = "one"
$y = "two"
$a = [pscustomobject]@{"x"=$x;"y"=$y}

测试上述案例:

$a

x   y
-   -
one two

$a.x
one
$a.y
two

我喜欢这个链接PSCustomObjects了解创建和使用自定义对象的说明。

使用函数进行测试:

function test {

param([string] $w)

$x = $w + "x"
$y = $w + "y"

[pscustomobject]@{"x"=$x; "y"=$y}
}

$a = test "my property "
$a

x             y
-             -
my property x my property y


$a.x
my property x
$a.y
my property y

关于powershell - 通过符号名称(键)访问脚本的多个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54985160/

相关文章:

performance - 为超大数据选择数据结构

Java 字符串 : Is hashcode actually the hashvalue?

c++ - 在 Makefile 中链接时定义变量的问题

c# - 即使其中一个键是整数,如何访问有序字典中的值?

c# - myCollection.Add() 与 myCollection ["key"的性能]

azure - 如何在 Azure PowerShell Runbook 上应用 SharePoint 网站模板?

regex - Powershell 'where'语句-notcontains

c - 如何在C中将a字符串拆分为单独的单词,其中空格不恒定?

powershell - 根据属性值获取通用/列表中对象的索引

windows - 如何安装Microsoft Windows Terminal