I've this command:
curl -s -L --header "PRIVATE-TOKEN:XXXX" https://myuri/"
And I need to convert to PowerShell
I've tried this, but doesn't works:
Invoke-RestMethod -Method Get -Headers #{"AUTHORIZATION"="XXXXXX"} -Uri https://myUri
I've also tried this:
PS > $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
PS > $headers.Add("Authorization","XXXXXX")
PS > $headers.Add("Accept","application/json")
PS > $headers.Add("Content-Type","application/json")
PS> $uri = "https://myUri"
PS> $response = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get -ContentType "application/json"
PS> $response
PS>
but the $response is empty.
Any help ?
Here is one that I used to authenticate to Teamcity
function Connect-to-Teamcity ($userName, $password, $tcServer, $uri)
{
$auth = $username + ':' + $password
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$EncodedPassword = [System.Convert]::ToBase64String($Encoded)
$headers = #{"Authorization"="Basic $($EncodedPassword)"}
$url = "http://$tcServer/httpAuth/app/rest"
$result = Invoke-RestMethod -Uri "$url/$uri" -Header $headers -Method Get
return $result
}
Here is another example if you have more than one header Item:
$resourceAppIdURI = "https://graph.windows.net"
# Login to Azure and get a token valid for accessing the graph API
$authority = "https://login.windows.net/$adTenant"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $redirectUri, "Auto")
# Add the token to the header of all future calls to the graph API
$headers = #{"Authorization"=$authResult.CreateAuthorizationHeader();"Content-Type"="application/json"}
$uri = [string]::Format("https://graph.windows.net/{0}/groups/{1}/appRoleAssignments?api-version=1.5", $adTenant, $groupId)
$body = #"
{
"id": $appRoleId,
"principalId": $groupId,
"principalType": "Group",
"resourceId": $appObjectId
}
"#
$result = Invoke-RestMethod -Method "POST" -Uri $uri -Headers $headers -Body $Body
Related
In PowerShell using Invoke-RestMetjhod to call different API´s I am stuck getting an InvalidOperation error when trying to pass both header and body information to the POST call.
My script is:
Set-StrictMode -Version Latest
$ApiToken = Get-Content ‘C:\APIEnergiNet\api_token.txt’
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $ApiToken")
$response = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/token' -Method 'GET' -Headers $headers
$GetMetringPointID = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meteringpoints/meteringpoints?includeAll=true' -Headers #{ Authorization = "Bearer " + $response.result }
foreach($result in $GetMetringPointID){
$CurrentMeteringID = $GetMetringPointID.result.meteringPointId
foreach($Currentresult in $CurrentMeteringID){
$MeterID = $Currentresult
$GetCharges = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/MeteringPoints/MeteringPoint/GetCharges' -Method 'POST' -Headers #{ Authorization = "Bearer " + $response.result } -Body #{ meteringPoints = #( #{meteringPoint = "$Currentresult" } ) }
$GetCharges
}
}
The API needs the following sent in the body :
{
"meteringPoints": {
"meteringPoint": [
"string"
]
}
}
if I create variable $postParams containing the data like this:
$postParams = #{
meteringPoints = #(
#{meteringPoint = "$MeterID" }
)
}
$postParams
it returns:
meteringPoints {System.Collections.Hashtable}
The API has a swagger here https://api.eloverblik.dk/customerapi/index.html
Can anyone help me why I get this error and how to fix it?
Best Regards
Stig :-)
UPDATE WITH LATEST CODE BELOW:
Set-StrictMode -Version Latest
$ApiToken = Get-Content ‘C:\APIEnergiNet\api_token.txt’
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer $ApiToken")
$response = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/token' -Method 'GET' -Headers $headers
$GetMetringPointID = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meteringpoints/meteringpoints?includeAll=true' -Headers #{ Authorization = "Bearer " + $response.result }
foreach ($result in $GetMetringPointID)
{
$CurrentMeteringID = $GetMetringPointID.result.meteringPointId
foreach ($Currentresult in $CurrentMeteringID)
{
$MeterID = $Currentresult
$postParams = #{
meteringPoints = #(
#{ meteringPoint = "$MeterID" }
)
} | ConvertTo-Json
$resultlist = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/MeteringPoints/MeteringPoint/GetCharges' -Method 'POST' -ContentType 'application/json' -Headers #{ Authorization = "Bearer " + $response.result } -Body #{ $postParams }
$resultlist
}
}
ERROR I NOW GET:
ParserError: C:\APIEnergiNet\api.ps1:31:245
Line |
31 | … Authorization = "Bearer " + $response.result } -Body #{ $postParams }
| ~
| Missing '=' operator after key in hash literal.
I've made this little PS for you based on yours
$Path = "C:\EnergiNet\"
$TokenFile = $Path + "token.txt"
$JSON_ResponseFile = $Path + "Response.json"
$XML_ResponseFile = $Path + "Response.xml"
$ApiToken = Get-Content $TokenFile
# Get Auth token #
$response = Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/token' -Method 'GET' -Headers #{ Authorization = "Bearer " + $ApiToken }
$Auth_Token = $response.result
$body = '{ "meteringPoints": {"meteringPoint": ["571313174xxxxxxxxxxx","571313174xxxxxxxxxxx","571313174xxxxxxxxxxx"] }}'
$headers = #{
'Authorization' = "Bearer " + $response.result
'Accept' = 'application/json'
}
Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meterdata/gettimeseries/2023-01-01/2023-02-01/Quarter' -Method 'POST' -ContentType 'application/json' -Headers $headers -Body $body | ConvertTo-Json -Depth 100 | out-file $JSON_ResponseFile
$headers = #{
'Authorization' = "Bearer " + $response.result
'Accept' = 'application/xml'
}
(Invoke-RestMethod 'https://api.eloverblik.dk/customerapi/api/meterdata/gettimeseries/2023-01-01/2023-02-01/Quarter' -Method 'POST' -ContentType 'application/json' -Headers $headers -Body $body).outerXml | out-file $XML_ResponseFile
Post Chat message using Graphapi via Powershell using Delegate Grant type using password grant
#Group chat Message
$granttype = 'password'
$tenantID = '695bbc7172e0'
$scope = 'https://graph.microsoft.com/.default'
$clientSecret = (ConvertTo-SecureString "O4UN4ndB" -AsPlainText -Force )
$cred = Import-Clixml C:\temp\credentials.xml
$redirectUri = "https://testexchangeewsdelegate.com"
# Construct URI
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
# Construct Body
$body = #{
clientId = "0e003e593d"
scope = $scope
grant_type = $granttype
username = $cred.UserName
password = $cred.GetNetworkCredential().password
}
$TokenResponses = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $ReqTokenBody
$apiUrl = 'https://graph.microsoft.com/v1.0/chats/19:987345050c22c8369df1a6#thread.v2'
Invoke-RestMethod -Headers #{Authorization = "Bearer $($Tokenresponses.access_token)"} -Uri $apiUrl -Method Get -ContentType "application/x-www-form-urlencoded"
$apiUrl1 = 'https://graph.microsoft.com/v1.0/chats/19:987345050c22c8369df1a6#thread.v2/messages'
$params = #{
Body = #{ Content = "Hello World"} }
$bodyJSON = $params| ConvertTo-Json
Invoke-RestMethod -Headers #{Authorization = "Bearer $($Tokenresponses.access_token)"} -Uri $apiUrl1 -Method Post -Body $bodyJSON -ContentType 'application/json'
Help me to update group chat post using PowerShell via graph api
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
I'm trying to create a command in Powershell that is an equivalent of
curl -u username:abcd -i -F name=files -F filedata=#employees.csv https://myservice.com/v1/employees/csv
I need to have file name in the request. So in Powershell
$FilePath = 'employees.csv'
$FieldName = 'employees.csv'
$ContentType = 'text/csv'
$username = "user"
$password = "..."
$FileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open)
$FileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new('form-data')
$FileHeader.Name = $FieldName
$FileHeader.FileName = Split-Path -leaf $FilePath
$FileContent = [System.Net.Http.StreamContent]::new($FileStream)
$FileContent.Headers.ContentDisposition = $FileHeader
$FileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($ContentType)
$MultipartContent = [System.Net.Http.MultipartFormDataContent]::new()
$MultipartContent.Add($FileContent)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($username):$($password)" ))
$Response = Invoke-WebRequest -Headers #{Authorization = "Basic $base64AuthInfo" } -Body $MultipartContent -Method 'POST' -Uri 'https://myservice.com/v1/employees/csv'
Is there a better (shorter) way of doing this so I have a file name in Content Disposition?
$body = get-content employees.csv -raw
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("user:pass" ))
Invoke-RestMethod -Headers #{Authorization = "Basic $base64AuthInfo" } -uri url -Method Post -body $body -ContentType 'text/csv
# a flag -ContentDispositionFileName would be great
Taking a guess with what your endpoint will accept, but here's an example of your curl request in powershell:
$u, $p = 'username', 'password'
$b64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${u}:$p"))
$invokerestmethodParams = #{
'Uri' = 'https://myservice.com/v1/employees/csv'
'Method' = 'POST'
'Headers' = #{ Authorization = "Basic $b64" }
'InFile' = 'C:\path\to\employees.csv'
'SessionVariable' = 's' # use $s to view content headers, etc.
}
$output = Invoke-RestMethod #invokerestmethodParams
I need to trigger a build after successful deployment of a release. I have tried using below code in Powershell in the release definition.
After executing, I get this error - Access is denied due to invalid credentials
$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?
api-version=2.0"
$body = "{ 'definition' : { 'id' : 1} }"
$type = "application/json"
$headers = #{
Authorization = "Basic d3JlblxzcsampleTIzNA=="
}
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -
Method Post -Headers $headers
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"`
Based on my test, you can use -UseDefaultCredentials :
$type = "application/json"
$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"
$body = "{ 'definition' : { 'id' : 56} }"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -UseDefaultCredentials
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"
Alternatively provide the specific Credential:
$user = "username"
$password = "password"
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$password)))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$type = "application/json"
$url = "http://abc:8080/tfs/GlobalCollection/Project/_apis/build/builds?api-version=2.0"
$body = "{ 'definition' : { 'id' : 56} }"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Body $body -ContentType $type -Method Post -Headers $headers
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"