你所展示的是字符串化的的形式自定义对象,它使用哈希表-like文本表示.
该自定义对象的定义如下所示:
# Construct a custom object with .ResourceType, .Id, and .Name properties.
$response = [pscustomobject] @{
ResourceType = 'UserStory'
Id = 202847
Name = 'Professional Lines: 2,800,000 Policy Aggregate Limit update'
}
If you include this variable in an expandable string (interpolating string), you'll get the representation in your question[1] - note that you'll get the same representation if you pass the object to the Write-Host cmdlet[2], as well as even with default output formatting if [pscustomobject]
instances are nested in property values:
# Note the enclosing "..."
PS> "$response"
@{ResourceType=UserStory; Id=202847; Name=Professional Lines: 2,800,000 Policy Aggregate Limit update}
# Custom object nested in a property value:
PS> [pscustomobject] @{ foo = [pscustomobject] @{ bar = 'baz' } }
foo
---
@{bar=baz}
请注意,如果没有包含"..."
,借助 PowerShell 的输出格式化系统,您将获得更好的表格表示形式。
PS> $response # direct output of the object
ResourceType Id Name
------------ -- ----
UserStory 202847 Professional Lines: 2,800,000 Policy Aggregate Limit update
假设$response
实际上仍然是一个自定义对象,而不是一个它的字符串表示,你可以简单地访问自定义对象的属性来构建字符串, again 使用一个可扩展字符串:
PS> "TP Id:$($response.Id) $($response.Name)"
TP Id:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update
使用时需要注意$(...)
围绕属性参考 - 请参阅这个答案有关 PowerShell 字符串扩展规则的摘要。
An 替代方法是使用-f
操作员,它使用类似于 .NET 的格式化字符串String.Format() method:
PS> 'TP ID:{0} {1}' -f $response.Id, $response.Name
TP ID:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update
[1] You can also obtain this representation by calling .psobject.ToString()
on a custom object; curiously, just .ToString()
doesn't work, as of PowerShell Core 6.1.0; this surprising discrepancy is discussed in this GitHub issue.
[2] Do note that Write-Host
's purpose is to provide for-display-only (to-host) output, which bypasses PowerShell's success output stream, and thereby the ability to capture or redirect its output - see this answer for more information.