I'm trying to call a PowerBI GETinfo Scanner API using PowerShell. One of the requirements is to pass multiple workspaces to get the info. Here is the MS doc link :\
https://learn.microsoft.com/en-us/rest/api/power-bi/admin/workspace-info-post-workspace-info#example
However, I'm not able to pass below syntax for API body in PowerShell.
The below syntax to call multiple workspaces in API body is not working :
$auth_body =#{
"workspaces": [
"97d03602-4873-4760-b37e-1563ef5358e3",
"67b7e93a-3fb3-493c-9e41-2c5051008f24"
]
}
I'm only able to pass single workspace and below syntax works :
$auth_body =#{'workspaces' ="3b7e9b1c-bdac-4e46-a39d-1b3d24a0e122"}
Please help me to form the syntax for multiple workspaces. Seems I'm not able to form key value pair inside PowerShell for multiple workspaces
Updated Code after applying MathiasR.Jessen suggestion:
$authority = 'https://login.microsoftonline.com/oauth2/'+ $tenantID
$authResult = Get-AdalToken -Authority $authority -Resource $resourceAppIdURI -ClientID $UId -Clientsecret $password -TenantID $tenantID
$Token=$authResult.AccessToken
#Write-Output "Token: $Token"
$auth_header = #{
'Accept' = "application/json";
'Authorization' = 'Bearer ' +$Token
}
$auth_body = #{
"workspaces" =
#("50c4bd8e-fc75-433e-a0cd-755f9329515e","97d03602-4873-4760-b37e-1563ef5358e3")
}
$uri = "https://api.powerbi.com/v1.0/myorg/admin/workspaces/getInfo"
$all_workspace = (Invoke-RestMethod -Uri $uri –Headers $auth_header -Body $auth_body –Method Post)
And Error Message :
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
+ ... rkspace1 = (Invoke-RestMethod -Uri $uri –Headers $auth_header -Body $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
However, It works perfectly if I provide single workspace.
You're mixing PowerShell and JSON syntax.
To define an array in PowerShell, use the #() array subexpression operator:
$auth_body = #{
"workspaces" = #(
"97d03602-4873-4760-b37e-1563ef5358e3",
"67b7e93a-3fb3-493c-9e41-2c5051008f24"
)
}
Related
So I'm trying to automate a process at work which involves hitting SendGrid's API. For a short explanation.. with SendGrid you have Subusers and underneath those Teammates. There is no ready option to search all teammates, so you have to supply a subuser then display all teammates underneath. Rinse, repeat down the line. Well I'd like to automated as best as I can.
So the idea is to collect a teammate email address from then user then dump into a variable all the subusers then loop through those subusers looking for the $email variable.
I've never actually used loops in my scripts over the years so it's new territory for me and combining it with an invoke-restmethod just boggles me. heres what Ive got so far:
$token = 'xxxxxxxxxxxxxxxxxxx'
#First uri is to pull a list of subusers
$uri = "https://api.sendgrid.com/v3/subusers"
#Prompts for target email address
$email = Read-Host "Enter the users email"
$headers1 = #{"Authorization" = "Bearer $token"}
$headers2 = #{"Authorization" = "Bearer $token"
"on-behalf-of" = "$subuser"
}
$subs = Invoke-RestMethod -Method get -uri $uri -headers $headers1
$subarray = $subs | select-object username
foreach ($su in $subarray){
$teamarray = invoke-restmethod -method get -uri "https://api.sendgrid.com/v3/teammates?limit=500&offset=0" -headers $headers2
#$teamarray.gettype()
}
The last line is commented out.. i was trying to find teh type of the $teamarray data but it's giving this error for each loop through the subusers:
invoke-restmethod : {"errors":[{"field":null,"message":"authorization required"}]}
At line:18 char:18
+ ... teamarray = invoke-restmethod -method get -uri "https://api.sendgrid. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodComma
nd
This should mean the invoke-restmethod is malformed somehow. Any pointers would be appreciated!
I'm struggling for last week or more with sending rest api command from powershell to add host in AWX(from curl is working). When I sent one parameter is worki but I need to send also variables
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic $VfAwxTokenX")
$Headers.Add('Content-Type', 'application/json')
$body = #{
name = '$vmname'
variables = 'test'
}| ConvertTo-Json
write-output $body
$response = Invoke-RestMethod 'https://awx/api/v2/inventories/2/hosts/' -Method 'POST' -Headers $headers -UseBasicParsing -Body $body
and error what i get:
{
"name": "wewewe",
"variables": "test" } Invoke-RestMethod : {"variables":["Cannot parse as JSON (error: Expecting value: line 1 column 1 (char 0)) or
YAML (error: Input type str is not a dictionary)."]} At line:32
char:13
$response = Invoke-RestMethod 'https://awx/api ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Maybe any one of users had that issue and now how to overcome it?
According to my research, the parameter variables should be defined as JSON or YAML format. For more details, please refer to here.
For more details about how to call the API, please refer to the blog.
the problem was prosaic
variables = 'test'
if i put anything else then test is working :/
We need to be able to programatically POST to the MS Graph API in order to bulk assign users to Access Packages, e.g.: https://learn.microsoft.com/en-us/graph/api/accesspackageassignmentrequest-post?view=graph-rest-beta&tabs=http#examples
I am trying things like this:
Invoke-RestMethod 'https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentRequests' -Method POST -ContentType 'application/json' -Body #{
"requestType": "AdminAdd",
"accessPackageAssignment":{
"targetId":"xxx",
"assignmentPolicyId":"xxx",
"accessPackageId":"xxx"
}
}
Unfortunately though I get errors like this:
At line:2 char:29
+ "requestType": "AdminAdd",
+ ~
Missing '=' operator after key in hash literal.
At line:2 char:29
+ "requestType": "AdminAdd",
+ ~
The hash literal was incomplete.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEqualsInHashLiteral
Does anyone know how I should be doing it please?
Additionally, we have MFA enforced so the standard $Cred = Get-Credential will not work. What should I use instead?
Thanks
There are several errors on the object syntax of your example:
In Powershell properties are assigned with =
Property names must not be quoted
Property assignments are separated with semicolon
The correct command would look like:
Invoke-RestMethod 'https://graph.microsoft.com/beta/identityGovernance/entitlementManagement/accessPackageAssignmentRequests' -Method POST -ContentType 'application/json' -Body #{
requestType = "AdminAdd";
accessPackageAssignment = {
targetId = "xxx";
assignmentPolicyId = "xxx";
accessPackageId = "xxx"
}
}
Regarding MFA, you need to either use AppTokens or OAuth.
I wanted to call Graph API endpoints through PowerShell as well. This was the script I ended up with:
Install-Module -Name MSAL.PS -RequiredVersion 4.2.1.3
Import-Module MSAL.PS
$clientId = "YOURCLIENTID"
$clientSecret = "YOURCLIENTSECRET"
$tenantId = "YOURTENANTID"
$ConfidentialClientOptions = New-Object Microsoft.Identity.Client.ConfidentialClientApplicationOptions -Property #{ ClientId = $clientId; ClientSecret = $clientSecret; TenantId = $tenantId }
$ConfidentialClient = $ConfidentialClientOptions | New-MsalClientApplication
$tokenObj = Get-MsalToken -Scope 'https://graph.microsoft.com/.default' -ConfidentialClientApplication $ConfidentialClient
$apiUrl = "https://graph.microsoft.com/beta/users?filter=signInActivity/lastSignInDateTime le 2021-06-21T00:00:00Z&`$select=userPrincipalName,displayName,mail,signInActivity"
$res = Invoke-RestMethod -Headers #{Authorization = "Bearer $($tokenObj.AccessToken)"} -Uri $apiUrl -Method Get
$res.value | select userPrincipalName, displayName, mail, #{L="LastSignInDateTime";E={$_.signInActivity.lastSignInDateTime}} | Sort-Object -Property LastSignInDateTime
I wrote a blog post about it as well: https://engineerer.ch/2021/07/01/how-to-use-powershell-to-call-graph-api-endpoints/
I am able to perform a GET Request from Jira successfully in Postman, but am unable to make the same request in Powershell due to an authentication error. I know that my credentials are correct because there are or GET Requests that are successful. My guess is that it has something to do with the URL (https://arnold.jira.com/admin/rest/um/1/user).
Since I know that my credentials are correct, I am not sure what else I can try.
# Create a new session using the Jira REST API
$user = 'john.rambo#arnold.com'
$pass = '8675309'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue;
Accept = 'application/json'
}
# Perform the GET Request
$UserEmail = 'dolf.lundgren#arnold.com'
$UserAttributeLink = 'https://arnold.jira.com/admin/rest/um/1/user?email=' + $UserEmail + '&expand=attributes'
$UserAttributes = Invoke-RestMethod ($UserAttributeLink) -Headers $Headers -Method GET -ContentType "application/json"
I expect to have the info returned, but am met with this error:
Invoke-RestMethod : User failed to authenticate
At line:12 char:19
+ ... ttributes = Invoke-RestMethod ($UserAttributeLink) -Headers $Headers ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Method: GET, Reques\u2026PowerShell/6.2.1
}:HttpRequestMessage) [Invoke-RestMethod], HttpResponseException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
In PowerShell, I was able to log in using HTTP Basic authentication For Mail Chimp.
$acctname = 'thisismyusername'
$password = 'thisismyapikey'
$params = #{
Uri = 'https://us14.api.mailchimp.com/3.0/';
Method = 'Get'; #(or POST, or whatever)
Headers = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($acctname):$($password)"));} #end headers hash table
} #end $params hash table
$var = Invoke-RestMethod #params
$var
When I try to get basic info on list thats id is "d3a7a4432d".
$URL = "https://us14.api.mailchimp.com/3.0/"
$Endpoint = "/lists/d3a7a4432d"
$URLMailChimp = "$URL$Endpoint"
$gist = Invoke-RestMethod -Method Get -Uri $URLMailChimp
I get this error message:
Invoke-RestMethod : {
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"API Key Missing",
"status":401,
"detail":"Your request did not include an API key.",
"instance":""
}
At line:7 char:9
+ $gist = Invoke-RestMethod -Method Get -Uri $URLMailChimp
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I don't understand how to pass it my API key again. I thought by logging it it solved the issue.
I don't use MailChimp, but unless the first invocation provides you with an access token (and the documentation as well as your error message don't look like it would) you need to provide the authentication header with every request.
$acctname = 'thisismyusername'
$password = 'thisismyapikey'
$URL = 'https://us14.api.mailchimp.com/3.0/'
$listID = 'd3a7a4432d'
$auth = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${acctname}:${password}"))}
$gist = Invoke-RestMethod -Method Get -Uri "$URL/lists/$listID" -Headers $auth