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
Related
Trying to make a powershell script that tracks link clicks.
I have three goals:
change destination to name
Filter out destinations that are not a file type
Only display name of file, not the URL or extension
# Set the API key and endpoint
$apiKey = "API-KEY"
$endpoint = "https://api.rebrandly.com/v1/links?&limit=100"
# Make the API call and store the response
$response = Invoke-RestMethod -Method GET -Uri $endpoint -Headers #{ "apikey" = $apiKey } | Format-Table -Property clicks, destination
$response
clicks destination
------ -----------
11 https://github.com/file1.ps1
4 https://github.com/file2.ps1
2 https://github.com/main.zip
1 https://www.instagram.com
Desired Result
clicks destination
------ -----------
11 file1
4 file2
2 main
Format-Table doesn't perform collection filtering hence is not the right cmdlet for this use case. Also, for 2 property objects, it is not needed at all since default formatting output will be a table by default for objects with 4 properties or less.
Invoke-RestMethod -Method GET -Uri $endpoint -Headers #{ "apikey" = $apiKey } | ForEach-Object {
$lastSegment = ($_.destination -as [uri]).Segments | Select-Object -Last 1
if([System.IO.Path]::GetExtension($lastSegment)) {
[pscustomobject]#{
Clicks = $_.Clicks
Name = [System.IO.Path]::GetFileNameWithoutExtension($lastSegment)
}
}
}
This is a modification of Santiagos answer.
I couldn't quite get his to work.
I'm sure this can be optimized however.
$apiKey = "API-KEY"
$endpoint = "https://api.rebrandly.com/v1/links?&limit=100"
$r = Invoke-RestMethod -Method GET -Uri $endpoint -Headers #{ "apikey" = $apiKey }
ForEach($l in $r){$s = ($l.destination -as [uri]).Segments[-1]
if([System.IO.Path]::GetExtension($s)) {
[pscustomobject]#{
Clicks = $l.Clicks
Name = [System.IO.Path]::GetFileNameWithoutExtension($s)
}
}
}
$result = New-Object System.Collections.ArrayList
ForEach ($repoElement in $Repo.value)
{
$repoId = $repoElement.id
$BranchCreatorUrl = "https://dev.azure.com/xyz/_apis/git/repositories/$repoId/refs?api-version=6.1-preview.1"
$CreateorInfo = (Invoke-RestMethod -Uri $BranchCreatorUrl -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
$url1= "https://dev.azure.com/xyz/_apis/policy/configurations?api-version=4.1"
$response = (Invoke-RestMethod -Uri $url1 -Method Get -UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)})
$obj=[pscustomobject]#{
RepositoryName = $repoElement.name
RepositoryId = $repoId
BranchName = $CreateorInfo.value.name
PolicyName = $response.value.type.displayname
}
$result += $obj
}
Write-Output $result
The above code gives an output
I want to show all the branch name as string and not in the form of object ie this way {..,...,...,..}
If this is just about for-display formatting, i.e. what is shown in the implicitly table-formatted display output, you can call Format-Table explicitly and use a calculated column to apply custom formatting to the BranchName column:
# Sample result.
$result = [pscustomobject]#{
RepositoryName = 'name'
RepositoryId = 'id'
BranchName = 'branch1', 'branch2', 'branch3'
PolicyName = 'policy'
}
# Use explicit Format-Table formatting with custom formatting of the
# 'BranchName' column.
$result | Format-Table RepositoryName,
RepositoryId,
#{ n='BranchName'; e={ $_.BranchName -join ', ' } },
PolicyName
The above yields a tabular display whose BranchName column doesn't have the enclosing { ... }, which PowerShell uses to indicate that the column value is an array (perhaps confusingly, because it looks like a script block):
RepositoryName RepositoryId BranchName PolicyName
-------------- ------------ ---------- ----------
name id branch1, branch2, branch3 policy
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
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:
I need some help with the following PS code:
$site1 = "www.site1.com"
$site2 = "www.site2.com"
$site3 = "www.site3.com"
$sites = $site1,$site2,$site3
$request = foreach ($site in $sites) {invoke-webrequest $site -method head}
if ($request.StatusCode -ne "200"){write-host "site is not working"}
The actual output of $request returns the headers of all 3 sites, so how do I get the exact site that failed the test?
Thanks in advance
Try something like this:
"www.site1.com","www.site2.com", "www.site3.com" |
ForEach-Object {
$response = Invoke-WebRequest $_ -Method Head
[PsCustomObject]#{
Site = $_
StatusCode = $response.StatusCode
}
}
You can filter the output by appending the following after the last bracket:
| Where-Object StatusCode -ne 200