从Invoke-RestMethod PSobject获取值

时间:2017-07-20 18:45:05

标签: powershell psobject

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

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

它返回此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

1 个答案:

答案 0 :(得分:2)

好吧,你有一些时髦的东西在那里。您作为Invoke-RestMethod的返回结果显示的值实际上是反序列化的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并发布结果。这将让我们确切知道接下来会发生什么。