假设我有script1.ps1
,其代码如下:
Function Renew_Token($token) {
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-Vault-Token", $token)
$response = Invoke-RestMethod -method POST -uri "https://vault.com:8243/v1/auth/token/renew-self" -ContentType 'application/json' -headers $headers
$response| ConvertTo-Json -depth 100
}
Function getValues($token) {
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-Vault-Token", $token)
$response = Invoke-RestMethod -method GET -uri "https://vault.com:8243/v1/secret/vault/development" -ContentType 'application/json' -headers $headers
$response.data| ConvertTo-Json -depth 100
}
Renew_Token $token
write-host "token renewed!"
write-host "Vault Values:"
getValues $token
这给了我这样的回复:
{
"request_id": "ghgdf5-yuhgt886-gfd76trfd",
"lease_id": "",
"renewable": false,
"lease_duration": 0,
"data": null,
"wrap_info": null,
"warnings": null,
"auth": {
"client_token": "i657ih4rbg68934576y",
"accessor": "t543qyt54y64y654y",
"policies": [
"default",
"vault"
],
"token_policies": [
"default",
"vault"
],
"metadata": null,
"lease_duration": 2000,
"renewable": true,
"entity_id": ""
}
}
token renewed!
Vault Values:
{
"abc": "1234",
"def": "897",
"klm": "something12"
}
现在考虑在Script2.ps1
中,我将其称为script1
$second_response = & ".\Script1.ps1"
当然,$second_response
将上面的2个响应存储为输出。
我怎样才能将第二个响应存储为Script2中表中的键/值?即这部分:
{
"abc": "1234",
"def": "897",
"klm": "something12"
}
$HashTable = @{ }
$HashTable.Add($second_response.key, $second_response.value)
换句话说,以某种方式$second_response
变量应该只存储此输出:
{
"abc": "1234",
"def": "897",
"klm": "something12"
}
注意:第二个响应是动态的。这意味着在不同的环境下可能会有不同的值。因此,我希望能够动态存储此响应中的内容,而不是对值进行硬编码
此外,我需要脚本1中的2个响应,因为我将script1用于其他目的,例如说我只想查看库内容。 script2将对来自script1的响应进行操作,因此为了方便和灵活,我将它们分开了
更新:按照@kuzimoto的建议,我删除了输出,并将响应从JSON转换回去,我从Script2获取了此输出:
abc: 1234
def: 897
klm: something12
答案 0 :(得分:1)
我无法发表评论,但是有两种可能:
您不需要提及是否需要第一组结果。否则,只需从Renew_Token函数中删除或注释掉这行$response| ConvertTo-Json -depth 100
。
您要将script1的输出作为纯文本传递给script2。只需将$second_response = & ".\Script1.ps1"
更改为$second_response = & ".\Script1.ps1" | ConvertFrom-Json
。然后,当您想访问第二个响应时,请使用$second_response[1]
,因为这两组JSON都已添加到自定义PS对象中,并且可以像访问数组一样单独访问。