Facing issue while getting response of API in Powershell - powershell

I trying to create a Powershell Script to check that my API's are working or not. I am able to hit the API using Invoke-RestMethod without any issue but I am unable to get API response.
I have tried Invoke-RestMethod and Invoke-WebRequest
$user = 'User'
$pass = 'Test123'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue
}
$url="MYAPIURL"
$person = #{
UserID='test'
Password='Test123'
}
$json = $person | ConvertTo-Json
$Result =Invoke-RestMethod -Uri $url -Headers $Headers -Body $json -Method Post -ContentType 'application/json'
Write-Host ($Result | Format-Table | Out-String)
Always getting blank in $Result. In Postman it's working fine.

Related

MS Graph query - Encoding UTF-8 does not work at Invoke-RestMethod

I am having an issue related to the encoding.
$usermailactivitydetail = Invoke-RestMethod -uri $uri -headers $headers -ContentType "text/plain; charset=utf-8"
$usermailactivitydetail variable :
İç test01 Bölge)
https://learn.microsoft.com/en-us/graph/api/reportroot-getemailactivityuserdetail?view=graph-rest-1.0
script:
$appid = 'APPID'
$tenantid = 'TENANTID'
$secret = 'SECRETID'
$body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $appid
Client_Secret = $secret
}
$ConnectionParameters=#{
Uri="https://login.microsoftonline.com/$tenantid/oauth2/v2.0/token"
Method ="POST"
Body = $body
}
$connection = Invoke-RestMethod #ConnectionParameters
$token = $connection.access_token
Connect-MgGraph -AccessToken $token
$headers = #{"Authorization" = "Bearer "+ $token}
$uri = "https://graph.microsoft.com/v1.0/reports/getEmailActivityUserDetail(period='D7')"
thanks,
UPDATE :
$usermailactivitydetail = Invoke-RestMethod -uri $uri -headers $headers
$result = $usermailactivitydetail.Replace('Report Refresh Date','Report Refresh Date')
$resultarray = ConvertFrom-Csv -InputObject $result
#Export result to CSV
$resultarray | Export-Csv "C:\output.csv" -NoTypeInformation -encoding utf8
As Jeroen suggested, try to download to a file to prevent Invoke-RestMethod from trying to interpret the data and get the encoding wrong. The file will contain the raw response from the server. Then force the encoding when reading the file through PowerShell.
$tempFilePath = (New-TemporaryFile).Fullname
Invoke-RestMethod -uri $uri -headers $headers -OutFile $tempFilePath
$usermailactivitydetail = Import-Csv $tempFilePath -Encoding UTF8
Remove-Item $tempFilePath

Error when sending message to AppDynamics through powerhsell using invoke-restmethod

I am trying to send a message to App Dynamics using 'Invoke-RestMethod' through powershell which is giving below error
Invoke-RestMethod : AppDynamics - Error report HTTP Status 400 - Event
summary is not specifiedtype Status reportmessageEvent summary is not
specifieddescriptionThe request sent by the client was syntactically
incorrect.
I am using below code to send message.
$JSONBody = #{
'#context'= 'http://schema.org/extensions'
'#type'= 'MessageCard'
'title' = 'Incoming Alert Test Message'
'text' = 'xyz'
'eventtype'='CUSTOM'
'customeventtype'='appDcustomevent'
}
$json = ConvertTo-Json $JSONBody -Depth 100
$headers = #{Authorization='Basic '+[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes('username#account:password'))}
$response = Invoke-RestMethod -Uri 'https://rest api url/events' -Proxy 'proxy url:80' -Method Post -Headers $headers -Body $json -ContentType 'application/json'
Please help me understand how to fix this issue as i have no clue.
Thanks in advance,
Usha.
Your request is missing the "summary" field as per the documentation: https://docs.appdynamics.com/appd/20.x/en/extend-appdynamics/appdynamics-apis/alert-and-respond-api/events-and-action-suppression-api#EventsandActionSuppressionAPI-CreateaCustomEvent
(Every field marked as Mandatory under "Input parameters" table must be included in the request)
Update:
Below is tested as working, seems the JSON version does indeed have issues - so switched to using query params and this works as intended.
$application_id = "<APPLICATION_NAME>"
$summary = "This_is_a_summary"
$severity = "INFO"
$eventtype = "CUSTOM"
$controller = "<CONTROLLER_URL_NO_PROTOCOL>"
$port = "8090"
$protocol = "http"
$account = "<ACCOUNT>"
$username = "<USERNAME>"
$password = "<PASSWORD>"
$controllerEndpoint = "controller/rest/applications/${application_id}/events"
$restURL = "${protocol}://${controller}:${port}/${controllerEndpoint}?severity=${severity}&summary=${summary}&eventtype=${eventtype}"
"$restURL"
$headers = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${username}#${account}:${password}"))}
$response = Invoke-RestMethod -Uri $restURL -Method Post -Headers $headers -Body $JSON -ContentType "application/json"
$response.content

graph api assign manager

I'm trying to assign the manager to a user in AAD the documentation says
PUT /users/{id}/manager/$ref
but i'm not sure what to feed the $ref variable. I've tried UPN and the ID, but I keep getting
The remote server returned an error: (400) Bad Request.
Here is how i'm trying to put the manager info, but clearly i'm not doing it right or I can't read the documentation from here
$Header = #{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
$bodyProcess = #{
id= "string aa9999a1-1111-11a2-abab-asfdas32"
}
$body = $bodyProcess | ConvertTo-Json
$Uri = "https://graph.microsoft.com/v1.0/users/4d5f6c5a-0e69-40b6-a86d-e825582add50/manager/$ref"
$UserData = Invoke-RestMethod -Uri $Uri -Headers $Header -Method PUT -ContentType "application/json" -Body $Body
Any help would be greatly appreciated.
thanks,
Here is the full script that works for me.
$Header = #{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
$bodyProcess = #{
"#odata.id"= "https://graph.microsoft.com/v1.0/users/aa9999a1-1111-11a2-abab-asfdas32"
}
$body = $bodyProcess | ConvertTo-Json
$Uri = 'https://graph.microsoft.com/v1.0/users/4d5f6c5a-0e69-40b6-a86d-e825582add50/manager/$ref'
Invoke-RestMethod -Uri $Uri -Headers $Header -Method PUT -ContentType "application/json" -Body $Body

Powershell Invoke-RestMethod Paging

I am trying to get a list of all users from our Azure B2C tenant.
With some help from the internet I was able to create the powershell script below. But the result is incomplete it only shows 100 users. After searching around I found I should probably do something with Paging but I can't get it to work.
Can someone help me to modify the script below to return all users?
# Application (client) ID, tenant Name and secret
$clientId = "**********"
$tenantName = "*********"
$clientSecret = "************"
$resource = "https://graph.microsoft.com/"
$ReqTokenBody = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $clientID
Client_Secret = $clientSecret
}
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$Url = "https://graph.microsoft.com/beta/users?$select=displayName"
$Data = Invoke-RestMethod -Headers #{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $Url -Method Get
$Users = ($Data |select-object Value).Value
$Users | Format-Table DisplayName -AutoSize
Ok i got it to work in Powershell Core (Version 7.1.3).
This is the code I ended up using.
# Application (client) ID, tenant Name and secret
$clientId = "**************"
$tenantName = "***************"
$clientSecret = "******************"
$resource = "https://graph.microsoft.com/"
$ReqTokenBody = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $clientID
Client_Secret = $clientSecret
}
$TokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$Url = "https://graph.microsoft.com/beta/users?$select=displayName"
$UserResponse = Invoke-RestMethod -Headers #{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $Url -Method Get -Verbose
$CloudUser = $UserResponse.Value
$UserNextLink = $UserResponse."#odata.nextLink"
while ($UserNextLink -ne $null) {
$UserResponse = (Invoke-RestMethod -Headers #{Authorization = "Bearer $($Tokenresponse.access_token)"} -Uri $UserNextLink -Method Get -Verbose)
$UserNextLink = $UserResponse."#odata.nextLink"
$CloudUser += $UserResponse.value
}
$CloudUser | Format-Table DisplayName -AutoSize
Most of the last 8 lines (or so) are repeated. You can factor it out like this:
$Url = "https://graph.microsoft.com/beta/users?$select=displayName"
$headers = #{Authorization = "Bearer $($Tokenresponse.access_token)"}
$CloudUser = #()
do {
$UserResponse = Invoke-RestMethod -Headers $headers -Uri $Url -Method Get -Verbose
$CloudUser += $UserResponse.Value
$Url = $UserResponse."#odata.nextLink"
} while ($Url)
Also, why not use the Graph PowerShell module for this? https://learn.microsoft.com/en-us/powershell/microsoftgraph

Unable to ingest JSON data into Azure Event Hub

I wrote the below Powershell script to get the JSON data from an API endpoint (https://data.melbourne.vic.gov.au/resource/vh2v-4nfs) and then write this data in JSON format to Azure Event hub. I am able to successfully get the data from the endpoint however the data is not getting ingested into Azure Event Hub.
Can anyone please let me know what's wrong with the below code:
$url = "https://data.melbourne.vic.gov.au/resource/vh2v-4nfs"
$apptoken = "k7lQcUCVFoROv7rQh9fSSXMkZ"
# Set header to accept JSON
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("X-App-Token",$apptoken)
$results = Invoke-RestMethod -Uri $url -Method get -Headers $headers
$results
$method = "POST"
$URI = "https://YOURNS.servicebus.windows.net/eh-streetparking/messages"
$signature = "SharedAccessSignature sr=YOURNS.servicebus.windows.net%2feh-streetparking&sig=K6bfL1VjW9FUcL0B5xaI%3d&se=16722&skn=eh-sap-streetparking"
#$authInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$signature"))
# API headers
$headers = #{
"Authorization"=$signature;
# "Content-Type"="application/json;type=entry;charset=utf-8";
"Content-Type"="application/json";
}
# execute the Azure REST API
foreach ( $result in $results)
{
Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $result
}
The value you have presented as the return result from your Invoke-RestMethod is actually a deserialized PowerShell object, not JSON. It appears to be having its quotes removed at some point too.
PSObject ($results) looks like this: $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"}
You can do this to access individual values:
$x.full_name
Finally, follow this syntax to send POST request:
$Cred = Get-Credential
$Url = "https://server.contoso.com:8089/services/search/jobs/export"
$Body = #{
search = "search index=_internal | reverse | table index,host,source,sourcetype,_raw"
output_mode = "csv"
earliest_time = "-2d#d"
latest_time = "-1d#d"
}
Invoke-RestMethod -Method 'Post' -Uri $url -Credential $Cred -Body $body -OutFile output.csv