I'm trying to make a request to the AccessPointsDetails endpoint of the Cisco Prime API and then loop through that to get all URL objects for the AccessPoints so I can get data on each of them.
I get the following output:
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3373245; $=3373245}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3413720; $=3413720}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3432295; $=3432295}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3432310; $=3432310}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3462672; $=3462672}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3497980; $=3497980}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3497993; $=3497993}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3512621; $=3512621}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/3526872; $=3526872}
VERBOSE: Making request to: #{#type=AccessPointDetails; #url=https://cpist/webacs/api/v3/data/AccessPointDetails/16162527426; $=16162527426}
#type #url $
----- ---- -
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3373245 3373245
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3413720 3413720
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3432295 3432295
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3432310 3432310
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3462672 3462672
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3497980 3497980
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3497993 3497993
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3512621 3512621
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/3526872 3526872
AccessPointDetails https://cpist/webacs/api/v3/data/AccessPointDetails/16162527426 16162527426
Here is the response JSON for one store as well:
{
"queryResponse": {
"#last": 9,
"#first": 0,
"#count": 10,
"#type": "AccessPointDetails",
"#requestUrl": "https://cpist/webacs/api/v3/data/AccessPointDetails?.group=0026",
"#responseType": "listEntityIds",
"#rootUrl": "https://cpist/webacs/api/v3/data",
"entityId": [
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3373245",
"$": "3373245"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3413720",
"$": "3413720"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3432295",
"$": "3432295"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3432310",
"$": "3432310"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3462672",
"$": "3462672"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3497980",
"$": "3497980"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3497993",
"$": "3497993"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3512621",
"$": "3512621"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3526872",
"$": "3526872"
},
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/16162527426",
"$": "16162527426"
}
]
}
}
I feel I may be a bit burnt and making a silly oversight?
Solution Code (See Accepted Answer):
Function allAP {
Write-Verbose "Getting all APs for Store $Store"
$storeApReq = "https://cpist/webacs/api/v3/data/AccessPointDetails.json?.group=$Store"
Write-Verbose "Making request to $storeApReq"
$Global:apIdListReq = Invoke-RestMethod -uri $storeApReq -method Get -ContentType 'application/json' -headers #{ Authorization = $auth }
$Global:apIdList = $apIdListReq.queryResponse.entityId
$Global:apIdCount = $apIdListReq.queryResponse."#count"
Write-Verbose "Found $siteAPCount APs in Sites Database. $apIdCount out of $siteAPCount APs found."
Write-Verbose "Response Received: $apIdList"
$Global:apIdURL = $apIdListReq.queryResponse.entityId
$Global:apURL = $apIdUrl.'#url'
Write-Verbose "Starting a loop."
ForEach($apIdURL in $apIdList) {
Invoke-RestMethod -uri $apURL -method Get -ContentType 'application/json' -headers #{ Authorization = $auth }
Write-Verbose "Making request to: $apURL"
$apURL
}
}
The biggest issue you're having is accessing the members of your returned object incorrectly. The Invoke-RestMethod is returning a pscustomobject representation of the JSON the application returns to you. Your example JSON looked like this:
{
"queryResponse": {
"#last": 9,
"#first": 0,
"#count": 10,
"#type": "AccessPointDetails",
"#requestUrl": "https://cpist/webacs/api/v3/data/AccessPointDetails?.group=0026",
"#responseType": "listEntityIds",
"#rootUrl": "https://cpist/webacs/api/v3/data",
"entityId": [
{
"#type": "AccessPointDetails",
"#url": "https://cpist/webacs/api/v3/data/AccessPointDetails/3373245",
"$": "3373245"
},
...
]
}
}
This gets transformed into pscustomobject:
[pscustomobject]#{
'queryResponse' = [pscustomobject]#{
'#last' = 9
'#first' = 0
'#count' = 10
'#type' = 'AccessPointDetails'
'#requestUrl' = 'https://cpist/webacs/api/v3/data/AccessPointDetails?.group=0026'
'#responseType' = 'listEntityIds'
'#rootUrl' = 'https://cpist/webacs/api/v3/data'
'entityId' = #(
[pscustomobject]#{
'#type' = 'AccessPointDetails'
'#url' = 'https://cpist/webacs/api/v3/data/AccessPointDetails/3373245'
'$' = '3373245'
}
...
)
}
}
I'm unsure why accessing .'#url' isn't working for you. Below is a working implementation of what you're trying to do.
function Get-AccessPoint
{
param
(
[Parameter(Position = 0, Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$Store
)
# function is accessing above-scope variables $auth and $siteAPCount
Write-Verbose "Retrieving APs for store $Store"
$uri = "https://cpist/webacs/api/v3/data/AccessPointDetails.json?.group=$Store"
Write-Verbose "Request: $uri"
$global:apIdListReq = Invoke-RestMethod -Uri $uri -ContentType application/json -Headers #{Authorization = $auth}
$global:apIdList = $apIdListReq.queryResponse.entityId
$global:apIdCount = $apIdListReq.'#count'
Write-Verbose "Found $siteAPCount APs in Sites Database. $apIdCount out of $siteAPCount APs found."
foreach ($entity in $apIdList)
{
Write-Verbose "Making request to $($entity.'#url')"
Invoke-RestMethod -Uri $entity.'#url' -ContentType application/json -Headers #{Authorization = $auth}
}
}
Related
I'm trying to send a e-mail with attachment with powershell, as soon as I add in the attachment, I get a 400 Bad Request error, while it works find without attachment. Hope someone has a clue...
Part added:
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.txt",
"contentType": "text/plain",
"contentBytes": "SGVsbG8gV29ybGQh"
}
]
Full request:
$Subject = "Subject2"
$Message = "Message2"
$Recipient = "testemailaddress"
$SaveToSentItems = $false
$Request=#"
{
"Message": {
"Subject": $(Escape-StringToJson $Subject),
"Body": {
"ContentType": "HTML",
"Content": $(Escape-StringToJson $Message)
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "$Recipient"
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "attachment.txt",
"contentType": "text/plain",
"contentBytes": "SGVsbG8gV29ybGQh"
}
]
},
"SaveToSentItems": "$(if($SaveToSentItems){"true"}else{"false"})"
}
"#
# Convert to UTF-8 bytes
$Request_bytes = [system.Text.Encoding]::UTF8.getBytes($Request)
$headers = #{
"Authorization" = "Bearer $($attributes.EXO)"
"Accept" = "text/*, multipart/mixed, application/xml, application/json; odata.metadata=none"
"Content-Type" = "application/json; charset=utf-8"
"X-AnchorMailbox" = (Read-AADIntAccesstoken $attributes.EXO).upn
"Prefer" = 'exchange.behavior="ActivityAccess"'
}
$url="https://outlook.office.com/api/v2.0/me/sendmail"
Invoke-RestMethod -UseBasicParsing -Uri $Url -Method Post -Headers $headers -Body $Request_bytes
Error:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:47 char:1
Invoke-RestMethod -UseBasicParsing -Uri $Url -Method Post -Headers $h ...
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I use this for send attachs in mails with ms graph in powershell
$attach = "C:\file.pdf"
$fileName = (Get-Item -Path $attach).Name
$base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($attach))
$message = '{
"message": {
"subject": "subject",
"body": {
"contentType": "HTML",
"content": "'+$body+'"
},
"importance": "high",
"toRecipients": [
{
"emailAddress": {
"address": "'+$mail+'"
}
}
],
"attachments": [
{
"#odata.type": "#microsoft.graph.fileAttachment",
"name": "'+$fileName+'",
"contentType": "text/plain",
"contentBytes": "'+$base64string+'"
}
],
},
"saveToSentItems": "true"
}'
$URL = "https://graph.microsoft.com/v1.0/users/xxxxxxxxxxxxxxxxxxxx/sendMail"
Invoke-RestMethod -Method POST -Uri $URL -Headers $headers -Body $message
Convert to Base64 string before insert in the request.
I guess you have your own "body"!
Regards.
I am trying to fetch a particular value from the JSON response of an invoke-web request. But the value is not capturing
Tried using the following script, where the $body contains the response.
$url = "http://localhost:9096/getMachineStatus"
$HTTP_Request = [System.Net.WebRequest]::Create($url)
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
$body = Invoke-WebRequest -Uri $url
The response of the above script:
{
"Name": "LocalTestMachine",
"Profile": "QA",
"Stacks": [
{
"Region": "Mumbai-1",
"State": "Stopped",
"StackName": "QA",
"StackCreationStatus": "CREATE_Success",
"Instances": [
{
"MachineName": "LocalMachine",
"IpAddress": "10.10.10.164",
"State": "stopped",
"InstanceId": "i-0777e90151b22da44",
"ImageId": "ami-0322ff2d8d099g56c",
"CustomImageName": "ubuntu-trusty-16.04",
"InstanceType": "m4.large",
"LaunchTime": "2019-09-04T02:42:36-04:00",
"AvailabilityZone": "Mumbai-1",
"Tags": [
{
"Key": "ProductLine",
"Value": "Cloud"
}]
}]
}]
}
I just want to retrieve the value associated with the object State which is Stopped.
I tried with
$currentVMState = $body | where {$_.State}
It is not working
To get the value of the first State item in the Stacks array, do this:
$json = $body | ConvertFrom-Json
$json.Stacks[0].State
returns
Stopped
First you need to convert the response to json:
$json = $body | ConvertFrom-Json
Then iterate the $json object to get the state value:
$json.stacks.instances | ForEach-Object { $_.State }
I am trying to use the Invoke-Restmethod to call a set of API's, but it fails with the below error, i have also posted the same json format, can some let me know what could be wrong ?
### Ignore TLS/SSL errors
add-type #"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
public bool CheckValidationResult(
ServicePoint srvPoint, X509Certificate certificate,
WebRequest request, int certificateProblem) {
return true;
}}
"#
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
#Create URL string for Invoke-RestMethod
$urlsend = 'https://' + 'vrslcm-01a.corp.local/lcm/api/v1/' + '/login'
#Credential
$Username = "admin#localhost"
$password = "VMware1!"
$basicAuth = "Basic " + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes("$($Username):$Password"))
$headers = #{
"description"= "Testing Authentication"
}
$body = #{
$raw= '{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}'
"mode"= $raw
}
Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $body -ContentType 'application/json'
Here is the sample jSON which iam trying to invoke via powershell, it consists of the header and the body. I need to understand how we could call the same jSON POSTMAN example via the PowerShell Invoke-RestMethod
"item": [
{
"name": "authorization",
"description": "",
"item": [
{
"name": "Login",
"event": [
{
"listen": "test",
"script": {
"type": "text/javascript",
"exec": [
"var response=JSON.parse(responseBody)",
"postman.setEnvironmentVariable(\"token\", response.token)"
]
}
}
],
"request": {
"url": "{{Server}}/lcm/api/v1/login",
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json",
"description": ""
}
],
"body": {
"mode": "raw",
"raw": "{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}"
},
"description": ""
},
"response": []
},
{
"name": "Logout",
"request": {
"url": "{{Server}}/lcm/api/v1/logout",
"method": "POST",
"header": [
{
"key": "x-xenon-auth-token",
"value": "{{token}}",
"description": ""
}
],
"body": {},
"description": ""
},
"response": []
}
]
},
make $raw to a hashtable like
$raw = #{
username=$Username
password=$Password
}
add this hashtable to the $body hashtable
$body = #{
mode= $raw
}
but now it still is a hashtable the api cannot use. thus convert it to json like
$jsonBody = $body | ConvertTo-Json
using $jsonBody should then work when used like
Invoke-RestMethod -Method POST -uri $urlsend -Headers $headers -Body $jsonBody -ContentType 'application/json'
Like the error states, the problem is your hash definition.
A null key is not allowed in a hash literal.
PowerShell tries to evaluate $raw as a hash table key. Since it hasn't been defined before it is null and fails because null is not allowed. Try it like this:
$raw= '{\n\t\"username\": \"admin#localhost\",\n\t\"password\": \"vmware\"\n}'
$body = #{
"mode"= $raw
}
I used MSGraph Explorer and PowerShell Invoke-RestMethod to query the same MSGraph API, but MSGraph Explorer returns way more details than the PowerShell command. Could this be a permission issue or I missed something in the PowerShell command.
Here is the URI, it is to retrieve the audit log for a particular directory change.
https://graph.microsoft.com/beta/auditLogs/directoryAudits/Directory_029A8_49125229
This is the output from MSGraph Explorer:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#auditLogs/directoryAudits/$entity",
"id": "Directory_029A8_49125229",
"category": "Core Directory",
"correlationId": "d534994f-61f4-4015-8040-c16f728ec8b3",
"result": "success",
"resultReason": "",
"activityDisplayName": "Update user",
"activityDateTime": "2018-10-04T05:41:19.9668303Z",
"loggedByService": null,
"initiatedBy": {
"app": null,
"user": {
"id": "1f5c2159-f515-4cea-a99c-11c6ce1f7a5e",
"displayName": null,
"userPrincipalName": "tom-admin#contoso.onmicrosoft.com",
"ipAddress": "<null>"
}
},
"targetResources": [
{
"#odata.type": "#microsoft.graph.targetResourceUser",
"id": "498b3884-f723-444c-9c01-b75ec2c0ef08",
"displayName": null,
"userPrincipalName": "Tom.Real#contoso.com",
"modifiedProperties": [
{
"displayName": "AssignedLicense",
"oldValue": "[\"[SkuName=ENTERPRISEPACK, AccountId=cdc4b90d-7fa9-4a, SkuId=6f94b900, DisabledPlans=[]]\"]",
"newValue": "[]"
},
{
"displayName": "AssignedPlan",
"oldValue": "[{\"SubscribedPlanId\":..., \"ServicePlanId\":\"50e68c76-46c6-4674-81f9-75456511b170\"}]",
"newValue": "[{\"SubscribedPlanId\":... 50e68c76-46c6-4674-81f9-75456511b170\"}]"
},
{
"displayName": "Included Updated Properties",
"oldValue": null,
"newValue": "\"AssignedLicense, AssignedPlan\""
},
{
"displayName": "TargetId.UserType",
"oldValue": null,
"newValue": "\"Member\""
}
]
}
],
"additionalDetails": [
{
"key": "UserType",
"value": "Member"
}
]
}
This is the output from Invoke-RestMethod:
{
"#odata.context": "https://graph.microsoft.com/beta/$metadata#auditLogs/directoryAudits/$entity",
"id": "Directory_029A8_49125229",
"category": "Core Directory",
"correlationId": "d534994f-61f4-4015-8040-c16f728ec8b3",
"result": "success",
"resultReason": "",
"activityDisplayName": "Update user",
"activityDateTime": "2018-10-04T05:41:19.9668303Z",
"loggedByService": null,
"initiatedBy": {
"app": null,
"user": {
"id": "1f5c2159-f515-4cea-a99c-11c6ce1f7a5e",
"displayName": null,
"userPrincipalName": "tom-admin#contoso.onmicrosoft.com",
"ipAddress": "\u003cnull\u003e"
}
},
"targetResources": [
{
"#odata.type": "#microsoft.graph.targetResourceUser",
"id": "498b3884-f723-444c-9c01-b75ec2c0ef08",
"displayName": null,
"userPrincipalName": "Tom.Real#contos.com",
"modifiedProperties": " "
}
],
"additionalDetails": [
{
"key": "UserType",
"value": "Member"
}
]
}
As you can see Invoke-RestMethod does not return any details under "additionalDetails".
This is my PowerShell script
Function GetAuthToken
{
param
(
[Parameter(Mandatory=$true)]
$TenantName
)
Import-Module Azure
$clientId = "ef9bcdf0-a675-4cd5-9ec3-fa549f9ee4cf"
$redirectUri = "https://RedirectURI.com"
$resourceAppIdURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$Credential = Import-Clixml -Path "C:\MIMA\tom_admin_cred.xml"
$AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName,$credential.Password
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId,$AADCredential)
return $authResult
}
if($Version -eq $null) {$Version='Beta'}
#------Get the authorization token------#
$token = GetAuthToken -TenantName $tenant
#------Building Rest Api header with authorization token------#
$authHeader = #{
'Content-Type'='application\json'
'Authorization'=$token.CreateAuthorizationHeader()
}
$uri = "https://graph.microsoft.com/beta/auditlogs/directoryAudits/Directory_029A8_49125229"
$results = Invoke-RestMethod -Uri $uri –Headers $authHeader –Method Get
$results |ConvertTo-Json
I believe everything is fine with your query and permissions, the results are different since for ConvertTo-Json cmdlet by default 2 levels of contained objects are included in the JSON representation.
So, if you want directoryAudit all properties to be included in result, Depth parameter needs to be specified explicitly, for example:
$results |ConvertTo-Json -Depth 3 #at least 3 levels for directoryAudit entry
Please find below request body I created in powershell with Patch method to create a bug in TFS. But not able to create a bug and gettign message that "TF401320: Rule Error for field Found In. Error code: Required, HasValues, InvalidEmpty.","typeName"..... I also attached error code here.
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$pass)))
function CreateJsonBody
{
$value = #"
[
{
"op": "add",
"path": "/fields/System.Title",
"value": "TestBug"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.TCM.ReproSteps",
"value": "Our authorization logic needs to allow for users"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Priority",
"value": "1"
},
{
"op": "add",
"path": "/fields/Microsoft.VSTS.Common.Severity",
"value": "2 - High"
}
]
"#
return $value
}
$json = CreateJsonBody
$uri = "http://xxx-xxxxx-006:8080/tfs/xxx/xxxxx/_apis/wit/workItems/"+"$"+"bug/?api-version=2.0"
Write-Host $uri
$result = Invoke-RestMethod -Uri $uri -Method Patch -Body $json -Credential
$credential -ContentType "application/json-patch+json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
But not getting response.
Below error is getting
{
"$id": "1",
"innerException": null,
"message": "TF401320: Rule Error for field Found In. Error code: Required, HasValues, InvalidEmpty.",
"typeName": "Microsoft.TeamFoundation.WorkItemTracking.Server.RuleValidationException, Microsoft.TeamFoundation.WorkItemTracking.Server, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a",
"typeKey": "RuleValidationException",
"errorCode": 600171,
"eventId": 3200
}
Please help me. I already write code to create bugs for another account but not able to do here.