大卫·麦金托什自己的回答 https://stackoverflow.com/a/21413763/45375效果很好,但应该注意的是,结果数组的元素对应于all默认输出的行,其中包括:
- 空的前导行和尾随行
- 两个标题行(包含列名称的行和分隔行)
Out-String
只需将您通常在控制台(终端)中看到的内容发送到字符串,默认情况下为single字符串,并与-Stream
as an array字符串(行)。
以下是 David 命令的一个变体,它删除了标题和空行:
[string[]] $l_array = ($l_table | Out-String -Stream) -ne '' | select -Skip 2
这个答案的其余部分显示how to 控制细节获得的字符串表示形式;它使用 PS v3+ 语法和内置别名%
for ForEach-Object
为简洁起见。
Note: For clarity, the sample input hashtable is called $ht
(not $l_table
) in the following examples; the PSv4+ .ForEach()
variants perform better.
-
Get all keys作为字符串数组:
[string[]] $ht.Keys
-
Get all values作为字符串数组:
[string[]] $ht.Values
-
Get a 自定义表示 of 键值对,格式为<key>=<value>
;注意.GetEnumerator()
需要发送键值对单独地通过管道;默认情况下,PowerShell 传递一个哈希表作为一个整体:
$ht.GetEnumerator() | % { "$($_.Name)=$($_.Value)" }
# or (PSv4+):
$ht.GetEnumerator().ForEach({ "$($_.Name)=$($_.Value)" })
请注意,虽然[string]
/ [string[]]
演员,这也适用于隐含地在字符串插值期间(内部"..."
,一个可扩展的字符串),可以很好地配合原始 https://learn.microsoft.com/en-us/dotnet/api/system.type.isprimitive.NET 类型(以及其他数字类型,例如[decimal]
and [bigint]
);一般来说,类型只会打印完整的内容类型名称,除非他们的.ToString()
方法被显式重写以返回更有意义的自定义表示(这是原始类型所做的事情,并且只有somePowerShell cmdlet 返回的非基本类型)。
另请注意,在可扩展字符串内使用数组(类似数据结构)会扩展到其元素与(很少使用)的值的(字符串化)元素串联$OFS
首选项变量,默认为空格字符。 (例如。,$a='one', 'two'; "$a"
扩展到'one two'
;也就是说,它相当于"$([string[]] $a -join ' ')"
- see 这个答案 https://stackoverflow.com/a/40445998/45375欲了解更多信息可扩展字符串(字符串插值)在 PowerShell 中。
一个简单的选择示例property一个值来在字符串中表示它:
# Sample hashtable containing a value of a non-built-in type,
# [System.Diagnostics.Process]
$ht = @{ one = 1; two = Get-Process -ID $PID }
# Use the `.Path` property to represent the value.
$ht.GetEnumerator() | % { "$($_.Name)=$($_.Value.Path)" }