I've managed the http requests as per Joey's earlier advice (which I used for the logout part). How do I do this part of the code in logic apps? Including the rest of the script for context.
<code>
$Grid.Payload | where {$_.PR_OWN -eq "SC-CO-001"} | Select-Object -Property PR_SNAM, PR_OWN, PR_NAME,
PR_ADD4, PR_TENR, PR_USER1 | Export-Clixml -Path "C:\Test\API\XML_Sample.xml"
$Grid.Payload | Select-Object -Property PR_SNAM, PR_OWN, PR_NAME, PR_ADD4, PR_TENR, PR_USER1 | Format-
Table -AutoSize
<pre>
#Core Parameters
$baseuri = "https://test"
$header = #{
"Accept" = "text/json"
"Content-Type" = "text/json"
}
$G_header = #{"Accept" = "text/json"}
#Login
Write-Output "Login ..."
$uri_login = $baseuri + "SPDEDJSONSERVICE.LOGIN"
$body_login = #{"method"="login";"username"="qqq";"password"="qqq"} | ConvertTo-Json
$Conn = Invoke-RestMethod -Method Post $uri_login -Headers $header -Body $body_login
$SessionID = $conn.sessionID
#This is where we would code the data extraction
Write-Output "Gathering Data ..."
$uri_DefGrid = $baseuri + "SPDEDMHAPI.GRIDGET"
$body_DefGrid =
#{"sessionID"=$SessionID;"FORMAT"="payload";"GRIDID"="PROP";"GRIDVIEW"="1";
"FROM"=0;"HITS"=100;"PROFILE"
=#(#{"PR_USER1"="GENERATED";"PR_NAME"="G*"});"ORDERBY"="PR_DATESOLD"} | ConvertTo-Json
$Grid = Invoke-RestMethod -Method Post $uri_DefGrid -Headers $header -Body $body_DefGrid
$Grid.Payload | where {$_.PR_OWN -eq "SC-CO-001"} | Select-Object -Property PR_SNAM, PR_OWN,
PR_NAME, PR_ADD4, PR_TENR, PR_USER1 | Export-Clixml -Path "C:\Test\API\XML_Sample.xml"
$Grid.Payload | Select-Object -Property PR_SNAM, PR_OWN, PR_NAME, PR_ADD4, PR_TENR, PR_USER1 |
Format-Table -AutoSize
#Logout
Write-Output "Logging Out ..."
$uri_logout = $baseuri + "SPDEDJSONSERVICE.LOGOUT"
$body_logout = #{"method"="logout";"sessionID"=$SessionID} | ConvertTo-Json
Invoke-RestMethod -Method Post $uri_logout -Headers $header -Body $body_logout
<code>
$Grid.Payload | where {$_.PR_OWN -eq "SC-CO-001"} | Select-Object -Property PR_SNAM
As I do not have your sample data, I use postman send request with below body:
{
"list": [{"author": "Dan Brown", "isbn": "123456", "title": "Digital Fortress","name":"aaa"},
{"author": "JK Rowling", "isbn": "234567", "title": "Harry Potter","name":"aaa"}]
}
1.Add body into When a HTTP request is received to generate schema.
2.Add compose to get the Array.
3.Use Condition with outputs('compose')['list'][0]['name'] is eq to aaa to achieve where attribute.
4.Use Select of Data Operations to achieve select attribute.
The whole steps as below:
Related
I'm getting the following response through an API and I'm trying to pull data out of the JSON response. I'm interested in only pulling the clone.href when clone.name = ssh.
response: {
"links": {
"clone": [
"#{href=ssh://sampleurl.com; name=ssh}",
"#{href=https://sampleurl.com; name=http}"
],
"self": [
"#{href=https://sampleurl.com}"
]
}
}
I'm using the following to call the API:
Invoke-RestMethod -Uri $uri -Headers $Header -Method POST -Body $Body|ConvertTo-Json
You can do this:
$result = Invoke-RestMethod -Uri $uri -Headers $Header -Method POST -Body $Body|ConvertTo-Json
$href = $result.links.clone | Where-Object Name -eq ssh | ForEach-Object href
$href # Output to console
This uses Where-Object to filter the clone array and ForEach-Object to extract the href property, using short form of ForEach-Object -MemberName href.
Alternatively you can use the following syntax:
$href = $result.links.clone.Where{ $_.Name -eq 'ssh' }.href
It uses PowerShell intrinsic method Where for filtering.
I need some mega guidance on my script below. I need to be able to iterate through a csv file that stores tenantNames, app_id, client_secret for my script and wrap a big ForEach loop around it in order for my script to get said data for each tenant inside the CSV:
I'm struggling to visualize the order of the For loops to be able to pass $Tenant, $customer_client_id and $customer_client_secret.
Arrays might be excessive, but it's the most stable way I know to avoid formatting issues etc...
Any assistance or ideas would be super helpful
$master_file = 'C:\temp\apps.csv'
$array_tenant = #()
$array_customer_client_id = #()
$array_customer_client_secret = #()
Import-Csv $master_file | ForEach-Object {
$array_tenant += $_.tenant
$array_customer_client_id += $_.app_id
$array_customer_client_secret += $_.cs
}
$Tenant = ''
$customer_client_id = ''
$customer_client_secret = ''
$Body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $customer_client_id
Client_Secret = $customer_client_secret
}
$ConnectGraph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/token" -Method POST -Body $Body
$Token = $ConnectGraph.access_token
$file = "C:\temp\$Tenant._users_with_licenses.csv"
$final_results = "C:\temp\$Tenant._results.csv"
$users_array = #()
$user_list = 'https://graph.microsoft.com/beta/users'
$users = Invoke-RestMethod -Headers #{Authorization = "Bearer $($Token)"} -ContentType 'application/json' -Uri $user_list -Method 'GET'
$users.value | Where-Object {$_.assignedLicenses -ne "null"} | Select-Object userPrincipalName | Export-Csv $file -NoTypeInformation
Import-Csv $file | ForEach-Object {
$users_array += $_.userPrincipalName
}
foreach ($item in $users_array) {
$auth_methods = "https://graph.microsoft.com/v1.0/users/$item/authentication/methods"
$get_auth_methods = Invoke-RestMethod -Headers #{Authorization = "Bearer $($Token)"} -ContentType 'application/json' -Uri $auth_methods -Method 'GET'
if (!$get_auth_methods.value) {$get_auth_methods | Export-Csv $final_results -Append -NoTypeInformation}
}
I am going on a whim here and guessing this is what you're after:
$masterFile = 'C:\temp\apps.csv'
Import-Csv -Path $masterFile |
ForEach-Object -Process {
$tenant = $_.tenant
$request = #{
Uri = "https://login.microsoftonline.com/$Tenant/oauth2/v2.0/token"
Method = "POST"
Body = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
client_Id = $_.app_id
Client_Secret = $_.cs
}
}
$connectGraph = Invoke-RestMethod #request
$token = $connectGraph.access_token
$filePath = "C:\temp\$Tenant._users_with_licenses.csv"
$finalResults = "C:\temp\$Tenant._results.csv"
$userRequest = #{
Uri = 'https://graph.microsoft.com/beta/users'
Method = "GET"
Headers = #{
Authorization = "Bearer $token"
ContentType = "application/json"
}
}
$usersGet = Invoke-RestMethod #userRequest
$users = $users.value | Where-Object -Property "assignedLicenses" -NE "null" | Select-Object -ExpandProperty "userPrincipalName"
$users | Export-Csv -Path $filePath -NoTypeInformation -Force
foreach ($user in $users)
{
$finalRequest = #{
Uri = "https://graph.microsoft.com/v1.0/users/$user/authentication/methods"
ContentType = "application/json"
Method = "GET"
Headers = #{
Authorization = "Bearer $Token"
}
}
$getAuthMethod = Invoke-RestMethod #finalRequest
if (-not$getAuthMethod) {
$getAuthMethod | Export-Csv -Path $finalResults -Append -NoTypeInformation
}
}
}
Without really seeing what you expect, quite hard to understand what you currently have. Hopefully this gets you in the right direction! I also made use of splatting as this is a good scenario on when to use it.
I am trying to iterate the result of a webrequest call through powershell
$response = Invoke-WebRequest -URI $apiUri -Method Get -UseBasicParsing
$response
Result:
StatusCode : 200
StatusDescription : OK
Content : {"tenants":[{"name":"default","active":true},{"name":"tenant1","active":true}]}
RawContent : HTTP/1.1 200 OK
...
Using ConvertFromJson
$parsed = $response.Content | ConvertFrom-Json
$parsed
Result:
tenants : {#{name=default; active=True}, #{name=tenant1; active=True}}
Now, I want to list all the "name" value like this
Name
--------
default
tenant1
I've tried iterating it using this script but can't get the result:
$parsed | Select-Object -Property name | ForEach-Object {
Write-Host $_.name
}
The code below will output a table of names:
$json = '{"tenants":[{"name":"default","active":true},{"name":"tenant1","active":true}]}'
$data = $json | ConvertFrom-Json
$data.tenants | ft name
#name
#----
#default
#tenant1
If you want to capture them into a variable as an array you can use a feature called Member Enumeration:
$names = $data.tenants.name;
$names
#default
#tenant1
So the following code produces a csv file with only the last row. I need all 5 rows (with the test file I'm using) to be populated and exported to a csv file.
$url = "https://example.com/api"
$data_type = "application/json"
$headers = #{
"Content-Type" = $data_type
"Accept" = "application/json"
}
$userId = ""
Import-CSV './userIds.csv' | ForEach-Object {
$userId = $_.id
$body = #{
Identity = $userId
Site = "site_name"
APIKey = "secret"
}
$body_json = $body | Convertto-JSON
$result = Invoke-RestMethod -Method 'Post' -Uri $url -Headers $headers -Body $body_json
}
$result | Export-Csv 'C:\scripts\powershell\output.csv' -NoType
I've tried $list += $result, but I just get a bunch of errors. Any ideas?
Looks like I figured out the magic...
$url = "https://example.com/api"
$data_type = "application/json"
$headers = #{
"Content-Type" = $data_type
"Accept" = "application/json"
}
$userId = ""
$list = #()
Import-CSV './userIds.csv' | ForEach-Object {
$userId = $_.id
$body = #{
Identity = $userId
Site = "site_name"
APIKey = "secret"
}
$body_json = $body | Convertto-JSON
$result = Invoke-RestMethod -Method 'Post' -Uri $url -Headers $headers -Body $body_json
$list += result
}
$list | Export-Csv 'C:\scripts\powershell\output.csv' -NoType
It doesn't make sense to me, because it's an array of tables... but if it works somehow merging the tables into one table... then I'm happy.
I am trying to fetch asset data from the Fresh client with Powershell. I am able to get any asset by typing it's name but I want to save some of the variables it returns so I can use it further.
$naam = Read-Host "Voer product naam in"
# Set global variables
$APIKey = 'Myapikey'
$EncodedCredentials = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $APIKey,$null)))
$HTTPHeaders = #{ "X-ApiKey" = $APIKey}
$HTTPHeaders.Add('Authorization', ("Basic {0}" -f $EncodedCredentials))
$HTTPHeaders.Add('Content-Type', 'application/json')
$URL = 'https://helpdesk.company.nl/cmdb/items/list.json?field=name&q='+$naam
(Invoke-WebRequest -Method Get -Uri $URL -Headers $HTTPHeaders ).content
The following are some of the values that return after I run the above
{"config_items":[{"id":25000477949,"name":"SYS-MB1334","description":null,"ci_type_id":25000015988,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"
I would like to save the name and id variable for example
Unfortunately, the JSON you show is invalid.
Suppose the json returned from
$output = (Invoke-WebRequest -Method Get -Uri $URL -Headers $HTTPHeaders ).Content
looks like:
{"config_items":
[{"id":25000477949,"name":"SYS-MB1334","description":null,"ci_type_id":25000015988,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"},
{"id":12345678901,"name":"SYS-MB9876","description":null,"ci_type_id":12358745896,"impact":1,"created_at":"2020-03-12T10:14:40+01:00","updated_at":"2020-04-24T16:42:42+02:00"}]
}
Then you can collect the properties you need from the config_items using:
$result = ($output | ConvertFrom-Json).config_items |
Select-Object #{Name = 'Id'; Expression = {$_.id}},
#{Name = 'Name'; Expression = {$_.name}}
# output on screen
$result
# output to CSV file
$result | Export-Csv -Path 'X:\TheOutput.csv' -NoTypeInformation
Output on screen would look like
Id Name
-- ----
25000477949 SYS-MB1334
12345678901 SYS-MB9876
Hope that helps