我目前在創建一個帶有 Invoke-RestMethod 和回圈的 api 的 powershell 腳本時遇到問題,我花了一整天的時間試圖找出我哪里出錯了,但我沒有設法想出一些東西。
這是我正在嘗試制作的代碼
$url = "/api/Rest/v1"
$Body = @{
Username = ""
Password = ""
Privatekey = ""
}
$apikey = Invoke-RestMethod -Method 'Post' -Uri $url/Authenticate -Body $body
$headers = @{
'Authorization' = $apikey
}
$allusers = Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers | ft -HideTableHeaders Id
foreach ($userid in $allusers)
{
echo $userid
Invoke-RestMethod -Uri $url/Users/$userid -Method Get -Headers $headers
echo "test"
}
我對驗證 $apikey 和 $allusers 沒有問題,因為它們似乎輸出了我需要的內容,但我認為我的問題與輸出格式表中的輸出有關,但我已經為每個嘗試了其他方法,但我沒有線索我哪里出錯了
所以我自己測驗了 Invoke-RestMethod 命令,它們按預期作業,但是當我嘗試上面的腳本時,我得到以下結果。
Invoke-RestMethod : {"Message":"User with specified id was not found."}
$allusers 的輸出為用戶 ID 顯示如下內容
dce502ed-e4b6-4b5e-a047-0bf3b34e98c6
dc1e60c1-99a7-479a-a7d6-0dc618c8dd5e
1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3
AKA 以下作業沒有問題并輸出我需要的內容
Invoke-RestMethod -Uri $url/Users/1bd98bb0-a9ee-46b5-8e2e-0e3146aab6b3 -Method Get -Headers $headers
我真的很感激對此的一些指導。
uj5u.com熱心網友回復:
標準建議適用:
Format-*cmdlet(例如Format-Table,其內置別名是ft)發出輸出物件,其唯一目的是為PowerShell 的顯示輸出格式化系統提供格式化指令。
簡而言之:只使用Format-*cmdlet 來格式化資料以進行 display,從不用于后續的編程處理- 請參閱此答案以獲取更多資訊。
因此,洗掉| ft -HideTableHeaders Id管道段并使用成員訪問列舉將所有.Id屬性值提取為 data。
$allusers = (Invoke-RestMethod -Uri $url/Users -Method Get -Headers $headers).Id
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523427.html
標籤:电源外壳休息
