从 Invoke-RestMethod PSobject 获取值

Get values from Invoke-RestMethod PSobject

我正在使用 Invoke-RestMethod 从我们的 HRIS(人力资源信息系统)中提取员工数据:

$employee = Invoke-RestMethod -Method Get -Headers $headers -Uri $URI -ContentType 'application/json'

它 returns 这个 PSobject 和我在引用这些值时遇到问题:

employees                                                                                                                                                                                                                                                        
---------                                                                                                                                                                                                                                                        
{@{account_id=12345; username=12345; is_locked=False; employee_id=12345; first_name=John; middle_initial=Roger; last_name=Doe; full_name=John Roger Doe}}

我正在尝试提取各个值以在脚本的其余部分中用作变量。


我尝试过的事情:

Write-Output ($employee | Select -ExpandProperty "first_name")

Write-Output $employee.Properties["first_name"].Value


按要求完成脚本

$APIkey = "supersecret"
$KronosAccount = Read-Host -Prompt 'Input your Kronos admin ID'
$KronosPassword = Read-Host -Prompt 'Input your Kronos password' -AsSecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($KronosPassword)
$PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

$loginheaders = @{}
$loginheaders.Add("Api-Key", $APIkey)
$loginheaders.Add("Accept", "application/json")


$json = @{
  credentials = @{
    username = $KronosAccount
    password = $PlainPassword
    company = '123456'
  }
}

$token = Invoke-RestMethod -Method Post -Headers $loginheaders -Uri https://secure3.saashr.com/ta/rest/v1/login -ContentType 'application/json' -Body (ConvertTo-json $json) 
$tokenvalue = ($token | Select -ExpandProperty "token")

$NewEmployeeID = Read-Host -Prompt 'Input the employee ID to create an account for'

$headers = @{}
$headers.Add("Api-Key", $APIkey)
$headers.Add("Accept", "application/json")
$headers.Add("Authentication", "Bearer $tokenvalue")

$URI = "https://secure3.saashr.com/ta/rest/v1/employees/?company=123456&filter=username::$NewEmployeeID"
$employee = Invoke-WebRequest -Method Get -Headers $headers -Uri $URI -ContentType 'application/json'

$employee.employees

好的,你那里有一些时髦的东西。您作为 Invoke-RestMethod 的 return 结果显示的值实际上是一个反序列化的 PowerShell 对象,而不是 JSON。它似乎也在某个时候删除了引号。

如果你这样做: $x = @{account_id="12345"; username="12345"; is_locked="False"; employee_id="12345"; first_name="John"; middle_initial="Roger"; last_name="Doe"; full_name="John Roger Doe"}

那么你可以这样做:

$x.full_name

并得到你想要的值。我认为您会想要联系托管该 API 的任何人,并让他们在那里解决此问题。

为确保客户端没有引入此问题,您能否将 Invoke-RestRequest 替换为 Invoke-WebRequest(它应该采用所有相同的参数)。然后 运行 $employee.rawContent 和 post 结果。这将让我们确切地知道接下来会发生什么。