粘贴和格式化API返回



我正在尝试获取文件夹id、名称和路径。我最终得到的是一个用于具有多个条目的id的属性,以及一个用于包含多个条目的路径的属性。到目前为止,我主要关注的是输出的最后一个变量。

function Get-Token ($adminUserName, $adminPassword, $adminDomain, $api){
try
{
$creds = @{
username = $adminUserName
password = $adminPassword
domain = $adminDomain
grant_type = "password"
}
$token = ""
#echo "----------------"
#echo "--Authenticate--"
#echo "----------------"
$response = Invoke-RestMethod "$uri/oauth2/token" -Method Post -Body $creds -ContentType "application/json"
if($response -and $response.access_token)
{
# echo ""
# echo "---------------------------------"
# echo "--Authenticatication Successful--"
# echo "---------------------------------"
# echo ""
$token = $response.access_token;
return $token;
}
else
{
echo "ERROR: Failed to authenticate."
return
}
}
catch [System.Net.WebException]
{
Write-Host "----- Exception -----"
Write-Host  $_.Exception
Write-Host  $_.Exception.Response.StatusCode
Write-Host  $_.Exception.Response.StatusDescription
$result = $_.Exception.Response.GetResponseStream()
$reader = New-Object System.IO.StreamReader($result)
$reader.BaseStream.Position = 0
$reader.DiscardBufferedData()
$responseBody = $reader.ReadToEnd()
Write-Host $responseBody
}
}
Write-Host "Start"
$adminUsername = 'myusername'
$adminPassword = 'mypassword'
$adminDomain = $null
$uri = "https://someplacewithanapi"
$api = "$uri/api/v1"
$token = Get-Token -adminUserName $adminUsername -adminPassword $adminPassword -api $api
Write-Host "Token is"
Write-Host $token
Write-Host "Get token end"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $token")
### DEFINE TLS1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$response = Invoke-RestMethod $api/folders -Method GET -Headers $headers
$response |Select-Object @{L='id';E={$_.records.id}}, @{L='path';E={$_.records.folderpath}} |Select-Object id, path -ExpandProperty path

我的输出看起来像这个

id                  path
--                  ----
{12, 20, 11, 10...} {APPLICATIONSWINDOWSCENTRIX, APPLICATIONSLINUXOLBDOCKER, APPLICATIONSWINDOWSOLBHOSTDATA, APPLICATIONSLINUX...}

我正试图让输出看起来像这个

id   Path
12 Applications
20 ApplicationsLinux

从注释继续,您可以利用powershell对$response中项目的隐式展开

$response.records |Select id,@{Name='Path';Expression='folderpath'}

请注意,该表达式没有{}$_-Mathias之前曾解释过,如果您实际上没有做任何特殊的事情,并且只想重命名属性,则可以使用此语法。

您也可以使用这样的循环显式地自己处理集合。

foreach($record in $response.records)
{
[PSCustomObject]@{
ID   = $record.id
Path = $record.folderpath
}
}

最新更新