Running multiple iteration API calls using Powershell - json

I need to run 1000 API calls for 1000 different URI's. I tried to run 1000 different URI in one go as shown below but the API has a limit of 1000 lines.
Is there a way to run this code 1000 times producing 1000 separate JSON files or in one JSON file without me having to run the URI with the powershell script indivdiually.
$access_token ="dfdfgdfgf45h5676rdffghfghfbazbfgjvdrtwsffrgr"
$LogPath ='C:\StackOVerflow'
$URI = 'https://api.web.ser/audits/a_80weqwepeopeoA'
'https://api.web.ser/audits/a_B0980kdfl;skfd'
'https://api.web.ser/audits/a_Csdfsdfsjlksdc'
'https://api.web.ser/audits/a_Tlksdjfalkjdff'
'https://api.web.ser/audits/a_Fldkfjlsfjdfdl'
'https://api.web.ser/audits/a_Fsdfsdfsdfsd34'
'https://api.web.ser/audits/a_G34gfgf4ffsdrf'
'https://api.web.ser/audits/a_Haere34534fdgf'
'https://api.web.ser/audits/a_Ifdl023lererew'
'https://api.web.ser/audits/a_Afrererl45645w'
$headers = #{“authorization” = “Bearer $access_token”}
$result = Invoke-RestMethod -Uri $URI -Headers $headers |ConvertTo-Json| out-file "$LogPath\id_ExtractLogs$(((get-date).ToString("yyyyMMdd"))).json"
$result

You cannot pass an array of uri to the Invoke-RestMethod cmdlet; they must be iterated.
Here's a working solution:
$uri = 'https://api.web.ser/audits'
$reportList = #(
'a_80weqwepeopeoA'
'a_B0980kdfl;skfd'
# .. etc.
)
$token = 'secret'
$headers = #{ Headers = #{ Authorization = "Bearer $token" }}
$logPath = 'C:\StackOverflow'
foreach ($report in $reportList) {
$stamp = Get-Date -Format FileDateTime
Invoke-RestMethod -Uri "$uri/$report" -OutFile "$logPath\id_$stamp.json" #headers
}

Related

MSGraph - Invoke-WebRequest (403) Forbidden

I have a delegate App with Directory.ReadWrite.All permissions and a PS script to auth users over the app. It works when I use GET but I'm getting Forbidden when try PATCH method
Here's the part of that script:
$uri = "https://graph.microsoft.com/v1.0/devices/1111-2222-3333-4444-5555"
$method = "PATCH"
$body = '{
"extensionAttributes": {
"extensionAttribute2": "text"
}
}'
Invoke-WebRequest -Method $method -Uri $uri -Body $body -ContentType "application/json" -Headers #{Authorization = "Bearer $token"} -UseBasicParsing -ErrorAction Stop
Another thing: when using device ObjectID to construct Uri I'm getting the 403 Forbidden but if I use a $filter over a DeviceID I get 405 Method not allowed. Does it mean it doesn't like a filter and have to stick with the ObjectID? Is there a way when I run the GET with $filter to save in a variable only ObjectID within JSON query?
Thanks
sorted it, I needed Directory.AccessAsUser.All and used this to get the objectId variable:
$DsregCmdStatus = dsregcmd /status
if($DsregCmdStatus -match "DeviceId")
{
$DeviceId = $DsregCmdStatus -match "DeviceID"
$DeviceId = ($DeviceId.Split(":").trim())
$DeviceId = $DeviceId[1]
}
# Find Id
$uri = "https://graph.microsoft.com/v1.0/devices?`$filter=deviceId eq '$DeviceId'"
$method = "GET"
# Run Graph API query
$query = Invoke-WebRequest -Method $method -Uri $uri -ContentType "application/json" -Headers #{Authorization = "Bearer $token"} -UseBasicParsing -ErrorAction Stop
$output = ConvertFrom-Json $query.Content
$id = $output.value
$id = $id.id
Write-Host "Machine ID is $id"

Handling Forward Slashes ("//") In URL PowerShell

I have a script that successfully parses data from a URL featuring JSON data.
However, when I add a new URL, that includes a colon (":") followed by two forward slashes ("//"), the code errors out. I feel it's due to how the script is interpreting ("://") in the URL.
I tried to replace ("://") with (":%2F%2F") in the URL parameter but, that did not work either.
Here's the script:
$cred = "[MY TOKEN]"
$headers = #{ Authorization = "Bearer $cred"; Accept = "application/json" }
$Output = Invoke-RestMethod `
-Method Get `
-Headers $headers `
-ContentType: "application/json" `
-Uri "https://www.example.com/id_user://234kjh-2234jh-45645l"
$result = $Output | ConvertTo-Json
$result
The error is as follows:
Invoke-RestMethod : {"baseType":"error","code":"ServerError","message":"users.com
\"234kjh-2234jh-45645l\" not found","status":500,"type":"error"}
At line:4 char:13
+ $Output = Invoke-RestMethod `

Powershell Script to create user and add to servicedesk suddenly not working

last year I created a PS script, that took care of automatically creating users and adding them to our servicedesk, we use a special user creation account for this, the credentials are locally saved in a text file. It all worked fine, however the script doesn't seem to work anymore, did the JIRA API change?
I get following error message: Invoke-Rest-Method: The remote server returned an error (401) Unauthorized at response = Invoke-Rest-Method -Uri...etc
I checked and our user creation account still has all the permissions to create users, I can manually create them and the log shows that the user also logs in normally through the script.
Hopefully somebody can help with my problem!
Here's the code:
$jiraCredentials = Get-Content -Raw -Path "C:\PowerShellScripts\New-AdUser\credentials.json" |ConvertFrom-Json
$bytes = [System.Text.Encoding]::ASCII.GetBytes("${$jiraCredentials.username}:${$jiraCredentials.password}")
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", $basicAuthValue)
$headers.add("X-Experimentalapi", "opt-in")
$headers.add("Content-Type", "application/json")
#$headers.add("X-Atlassian-Token", "nocheck")
$JSON = #"
{
"fullName": "$emailAddressClean",
"email": "$emailAddressClean"
}
"#
$response = Invoke-RestMethod -Uri https://jira.dilax.com/rest/servicedeskapi/customer -Method POST -Body $JSON -ContentType "application/json" -Headers $headers
#add customer to servicedesk
$JSON2 = #"
{
"usernames":[
"$emailAddressClean"
]
}
"#
$response2 = Invoke-RestMethod -Uri https://jira.dilax.com/rest/servicedeskapi/servicedesk/9/customer -Method POST -Body $JSON2 -ContentType "application/json" -Headers $headers
managed to fix it because the log in credentials didn't get transmitted correctly:
$jiraCredentials = Get-Content -Raw -Path "C:\PowerShellScripts\New-AdUser\credentials.json" |ConvertFrom-Json
$user = $jiraCredentials.username
$pass = $jiraCredentials.password
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"

Only see ' rows=System.Object[] ' when enumerating JSON results in Powershell

I am returning a web service call that supposedly comes back in json format, and it does indeed appear to be valid json. As a string, it looks like this:
{"total":10,"rows":[{"process":"VISIO.EXE","computer_id":57,"last_used":"2016-04-20T01:34:09Z"},{"process":"VISIO.EXE","computer_id":64,"last_used":"2016-04-01T04:09:35Z"},{"process":"VISIO.EXE","computer_id":181,"last_used":"2016-03-10T23:02:53Z"},{"process":"VISIO.EXE","computer_id":230,"last_used":"2016-04-19T05:31:32Z"},{"process":"VISIO.EXE","computer_id":237,"last_used":"2016-04-04T10:23:23Z"},{"process":"VISIO.EXE","computer_id":284,"last_used":"2016-04-15T10:54:29Z"},{"process":"VISIO.EXE","computer_id":8401,"last_used":"2016-05-12T21:55:39Z"},{"process":"VISIO.EXE","computer_id":9045,"last_used":"2016-05-12T08:10:40Z"},{"process":"VISIO.EXE","computer_id":9527,"last_used":"2016-05-11T00:49:11Z"},{"process":"VISIO.EXE","computer_id":10198,"last_used":"2016-05-06T06:59:29Z"}]}
I am trying to enumerate through the results, using the following script. I have tried all of the listed options 1-4 by uncommenting them out one at a time, but I cannot get more than one result to return.
Any ideas as to what I'm doing wrong?
$url = 'https://servername:port/api/sam/raw_app_usage_property_values?criteria={"and":[["process","=","visio.exe"]]}&limit=100&columns[]=process&columns[]=computer_id&columns[]=last_used'
# option 1. get all results, we see a full list of processes, full string returned
#$results = Invoke-WebRequest -Uri $url -Method GET -Headers $headers
#write-host $results
# option 2. get all results but break them down as part of the request. Only one result returned - #{total=10; rows=System.Object[]}
#$results = Invoke-WebRequest -Uri $url -Method GET -Headers $headers | ConvertFrom-Json
#write-host $results
# option 3. use a different method, which supposedly breaks down the request natively. Only one result returned - #{total=10; rows=System.Object[]}
#$results = Invoke-RestMethod -Uri $url -Method GET -Headers $headers
#write-host $results
# option 4. get content directly from file, only one result returned - #{total=10; rows=System.Object[]}
#$results = (Get-Content -path "C:\temp\raw_app_usage_property_values.json" -raw)
# is there anything in the array?
foreach ($result in $results) {
write-host $result
}
You seem to be getting the data back. Remember that the returned object has two properties, "total" and "rows".
Try:
foreach ($result in $results.rows) {
write-host $result
}

Querying a site for a specific value [duplicate]

Can some one help me with the powershell v2 version of the below cmdlet.
$body =
"<wInput>
<uInputValues>
<uInputEntry value='$arg' key='stringArgument'/>
</uInputValues>
<eDateAndTime></eDateAndTime>
<comments></comments>
</wInput>"
$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)
$output = Invoke-WebRequest -Uri $URI1 -Credential $credential -Method Post -ContentType application/xml -Body $body
$URI1 = "<your uri>"
$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)
$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$request.Credentials = $credential
# $request | Get-Member for a list of methods and properties
try
{
$requestStream = $request.GetRequestStream()
$streamWriter = New-Object System.IO.StreamWriter($requestStream)
$streamWriter.Write($body)
}
finally
{
if ($null -ne $streamWriter) { $streamWriter.Dispose() }
if ($null -ne $requestStream) { $requestStream.Dispose() }
}
$res = $request.GetResponse()
Here, give this a shot. I provided some in-line comments. Bottom line, you're going to want to use the HttpWebRequest class from the .NET Base Class Library (BCL) to achieve what you're after.
$Body = #"
<wInput>
<uInputValues>
<uInputEntry value='$arg' key='stringArgument'/>
</uInputValues>
<eDateAndTime></eDateAndTime>
<comments></comments>
</wInput>
"#;
# Convert the message body to a byte array
$BodyBytes = [System.Text.Encoding]::UTF8.GetBytes($Body);
# Set the URI of the web service
$URI = [System.Uri]'http://www.google.com';
# Create a new web request
$WebRequest = [System.Net.HttpWebRequest]::CreateHttp($URI);
# Set the HTTP method
$WebRequest.Method = 'POST';
# Set the MIME type
$WebRequest.ContentType = 'application/xml';
# Set the credential for the web service
$WebRequest.Credentials = Get-Credential;
# Write the message body to the request stream
$WebRequest.GetRequestStream().Write($BodyBytes, 0, $BodyBytes.Length);
This method downloads binary content:
# PowerShell 2 version
$WebRequest=New-Object System.Net.WebClient
$WebRequest.UseDefaultCredentials=$true
#$WebRequest.Credentials=(Get-Credential)
$Data=$WebRequest.DownloadData("http://<url>")
[System.IO.File]::WriteAllBytes("<full path of file>",$Data)
# PowerShell 5 version
Invoke-WebRequest -Uri "http://<url>" -OutFile "<full path of file>" -UseDefaultCredentials -ContentType