gpt4 book ai didi

powershell - 解析Powershell变量

转载 作者:行者123 更新时间:2023-12-03 01:03:05 24 4
gpt4 key购买 nike

你们都提供了很大帮助-让我首先开始这样说。

我从运行的函数中获得以下输出-数据存储在一个名为$response的变量中,该变量是从Invoke-RestMethod调用获得的。

@{ResourceType=UserStory; Id=202847; Name=Professional Lines: 2,800,000 Policy Aggregate Limit update}    

我该如何将这些值解析为新变量,以便最终结果是
TP Id:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update

最佳答案

您所显示的是自定义对象的字符串化形式,该对象使用类似于哈希表的文本表示形式
该自定义对象的定义如下所示:

# 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'
}
如果将此变量包含在可扩展字符串(插值字符串)中,则会在问题中得到表示形式[1]-请注意,如果将对象传递给 Write-Host cmdlet ,您将获得相同的表示形式[[ 2]:
PS> "$response"  # Note the enclosing "..."
@{ResourceType=UserStory; Id=202847; Name=Professional Lines: 2,800,000 Policy Aggregate Limit update}
请注意,如果没有封闭的 "...",您将得到一个更好的表格表示形式,这是由PowerShell的输出格式系统提供的。
PS> $response  # direct output of the object

ResourceType Id Name
------------ -- ----
UserStory 202847 Professional Lines: 2,800,000 Policy Aggregate Limit update

假设$response实际上仍然是一个自定义对象,而不是它的字符串表示形式,您可以简单地 访问该自定义对象的属性来构建您的字符串,再次使用可扩展字符串来创建 :
PS> "TP Id:$($response.Id) $($response.Name)"
TP Id:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update
请注意需要在属性引用周围使用$(...)-有关PowerShell的字符串扩展规则的摘要,请参见this answer

替代方法是使用 -f运算符,它使用.NET String.Format() 方法之类的格式字符串:
PS> 'TP ID:{0} {1}' -f $response.Id, $response.Name
TP ID:202847 Professional Lines: 2,800,000 Policy Aggregate Limit update

[1]您还可以通过在自定义对象上调用.psobject.ToString()来获得此表示形式;奇怪的是,从PowerShell Core 6.1.0开始,仅.ToString()不起作用。在this GitHub issue中讨论了这种令人惊讶的差异。
[2]请注意Write-Host的目的是提供仅用于显示(到主机)的输出,该输出绕过PowerShell的成功输出流,从而具有捕获或重定向其输出的能力-有关更多信息,请参见this answer

关于powershell - 解析Powershell变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53107236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com