Hi I have been trying to do a web request call to sqlpad.
I have got the basis of the script to make the connection
Invoke-WebRequest -uri
However when I run the command I get connection 200 showing it has made a connection but how do I use cached cookies or how do I sign into sqlpad using credentials and run query all from using web request.
Sorry I am new to powershell and webrequest so I appreciate all your advice thank you.
That should be doable. You'd need to use sqlpad api. To keep cookies you need to create a session variable when calling signin and reuse it in later calls. To extract query data you'd need to use query-result end point. You need to know connectionId (can lookup at api/connections using browser) and SQL code (query text). Turns out there is no direct way to run query by query name. So you either need to know the sql of the query or you can extract it from /api/queries for specific query
$baseUrl = "http://localhost:39325/api"
$user = "yourEmail"
$password = "yourPassword"
$signinUrl = "$baseUrl/signin?email=$user&password=$password&redirect=false"
# sign in and create session variable $ws
if(!$ws) { $r = Invoke-WebRequest -Uri $signinUrl -SessionVariable ws -Method Post } else { Write-Host "connected"}
# list of available queries and connections. May need to run this to determine connection id or existing query sql
$QueryList = Invoke-RestMethod -Uri "$baseUrl/queries" -WebSession $ws
$ConnectionList = Invoke-RestMethod -Uri "$baseUrl/connections" -WebSession $ws
Write-Host "Available queries:"
$QueryList.queries | select name, connectionId, queryText | ft -AutoSize
# Execute Query
$params = #{
connectionId = "vhsNXMXCJeI9QlUL" #use $ConnectionList var or just look up on http://localhost:39325/api/connections/
cacheKey = "null" #just some dummy value, parameter is required but it's not really affecting anything
queryName = "test2" #optional
queryText = "select top 15 * from sys.columns" # required
} | ConvertTo-Json
$head = #{'Content-Type'='application/json'}
$data = Invoke-RestMethod -Uri "$baseUrl/query-result" -Method Post -Body $params -Headers $head -WebSession $ws
$data.queryResult.rows | ft
Related
I am creating an Azure pipeline where I need to make a rest api call from the pipeline then use part of the api call response in the request of another consecutive rest api call.
How can I achieve that?
In my test, I use the script below to get the work item state value in the pipeline, and you could use this variable in your script or pipeline for other api calls.
1.I transfer the api result into json with variable $field
2.Write-host the value $field
3.Get the element of system.state and set it as variable $witstate
4.Write-host the value.
# Define organization base url, PAT, linked wit, Target WIT state and API version variables
$orgUrl = "https://dev.azure.com/{yourORG}/{yourPROJECT}"
$pat = ""
$queryString = "fields=system.state&api-version=7.0"
$witID = {YourWitID}
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
# Get the linked wit state
$projectsUrl = "$orgUrl/_apis/wit/workitems/$witID?$queryString"
$field = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header | ConvertTo-Json | ConvertFrom-Json | Select-Object -ExpandProperty fields
write-host $field
$witstate = $field.'System.State'
Write-Host $witstate
I'm performing a query to output logs captured in an Azure Log Analytics Workspace, for example:
Invoke-AzOperationalInsightsQuery -WorkspaceId '' -Query "AzureDiagnostics | where Category == 'AzureFirewallApplicationRule'"
However I need to send the results of this to an Event Hub for further processing.
I'm trying to use the REST API (https://learn.microsoft.com/en-us/rest/api/eventhub/send-batch-events) but struggling to dynamically generate a request body to send to the Event Hub based on the output fields of the query. This may not be the best way to do it, any suggestions?
I suggest you can use Send event api by sending a simple json data one by one. Because if you use send batch api, you should build a more complex source data.
You can use the following powershell code to send data to event hub using send event api.
$queryResults = Invoke-AzOperationalInsightsQuery -WorkspaceId "xxx" -Query "your query"
#generate sas token
$URI_1 = "event_hub_namespace.servicebus.windows.net/eventhub_path"
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="the key"
#Token expires now+3000
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+3000
$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI_1)+ "`n" + [string]$Expires
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)
$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))
$Signature = [Convert]::ToBase64String($Signature)
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI_1) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name
$SASToken
$method = "POST"
$url = "https://event_hub_namespace.servicebus.windows.net/eventhub_path/messages"
$signature = $SASToken
# API headers
$headers = #{
"Authorization"=$signature;
"Content-Type"="application/atom+xml;type=entry;charset=utf-8";
}
#use foreach to send data
foreach($s in $queryResults.Results){
#Write-Output "hello"
$json = $s | ConvertTo-Json
#Write-Output $json
Invoke-WebRequest -Method $method -Headers $headers -Body $json -uri $url
}
Write-Output "**completed**"
After execute the powershell, I use code to receive the data from event hub, and I can confirm that all the data are sent to event hub. The screenshot as below:
Hi im trying to make a power shell script that can automate the enable for the data refresh schedule. can anyone help me with that?
$rs2010 = New-WebServiceProxy -Uri "URL HERE" -Namespace
SSRS.ReportingService2010 -UseDefaultCredential;
$rs2010.Timeout = 3600000
$schedules = $rs2010.ListSchedules("URL HERE");
Write-Host "--- Disabled Schedules ---";
Write-Host "----------------------------------- ";
$schedules | WHERE { $_.ScheduleStatename -ne 'Ready' }
**strong text**
i have this that can output disabled schedules. i need help to make a powershell script that can enable the data refresh whenever its turn off.
/Adel
EDIT:::
so i got this code
$rs2010 = New-WebServiceProxy -Uri
"http://url here/_vti_bin/ReportServer/ReportService2010.asmx"
-Namespace SSRS.ReportingService2010 -UseDefaultCredential;
$subscription = $rs2010.ListSubscriptions("http://url here/")
| Where-Object {$_.ScheduleStatename -ne "Ready" } ;
ForEach ($subscription in $subscriptions)
{
$rs2010.EnableDatasource($subscription.SubscriptionID);
$subscription | select subscriptionid, report, path
}
but i get this error
Exception calling "EnableDataSource" with "1" argument(s): "The path of the item 'bda17ed4-81a5-40a6-bade-894ecde02373' is not valid. The full path must be less than 260 characters long;
other restrictions apply. If the report server is in native mode, the path must start with slash. ---> Microsoft.ReportingServices.Diagnostics.Utilities.InvalidItemPathException:
I would like to retrieve account balance through Coinbase API with Powershell.
I coded the following reading from coinbase api documentation but the last request throws the following error:
Invoke-RestMethod : {"errors":[{"id":"authentication_error","message":"invalid signature"}]}
Here is my code.
What's wrong? Thank you.
$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch
$method = 'GET'
$requestpath = '/v2/accounts'
$secret_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Convert]::FromBase64String($secret_key)
$signature = $hmacsha.ComputeHash([Text.Encoding]::ASCII.GetBytes($sign))
$signature = [Convert]::ToBase64String($signature)
$header = #{
"CB-ACCESS-SIGN"=$signature
"CB-ACCESS-TIMESTAMP"=$epochtime
"CB-VERSION" = '2017-08-07'
"CB-ACCESS-KEY"='xxxxxxxxxxxxxx'
}
Invoke-WebRequest $accounts -Headers $header
Hopefully this will get you going. I just started working on a module today and got stuck on the same thing. I came across your question while trying to solve the problem myself. Figured I would share what I found. Good luck!
$accounts = 'https://api.coinbase.com/v2/accounts'
$time = 'https://api.coinbase.com/v2/time'
$epochtime = [string]((Invoke-WebRequest $time | ConvertFrom-Json).data).epoch
$method = 'GET'
$requestpath = '/v2/accounts'
$secret_key = (Get-CoinBaseAPIKeys).Secret
$sign = $epochtime + $method + $requestpath
$hmacsha = New-Object System.Security.Cryptography.HMACSHA256
$hmacsha.key = [Text.Encoding]::UTF8.GetBytes($secret_key)
$computeSha = $hmacsha.ComputeHash([Text.Encoding]::UTF8.GetBytes($sign))
The LONG WAY, for reference:
$signature = ""
foreach ( $c in $computeSha )
{
$signature += "{0:x2}" -f $c
}
The short way. Oddly I got stuck on this SAME issue, because the short way
produces UPPER CASE HEX and the long way ^^above^^ converts to lower case HEX.
The CoinBase API will ONLY accept the signature in HEX in lower case.
$signature = ([System.BitConverter]::ToString($computeSha) -replace "-").ToLower()
Now that we have the signature figured out, the rest should work great. I removed the CB_VERSION because it will default to your OWN API version. My default was different, so I simply removed it.
$header = #{
"CB-ACCESS-SIGN"=$signature
"CB-ACCESS-TIMESTAMP"=$epochtime
"CB-ACCESS-KEY"=(Get-CoinBaseAPIKeys).Key
}
$result = Invoke-WebRequest $accounts -Headers $header -Method Get -ContentType "application/json"
$accounts = $result.Content | ConvertFrom-Json
Write-Output $accounts.data
As an aside on storing PRIVATE KEY/SECRET you can find some ideas here:
https://github.com/cmaahs/BittrexAPI/tree/master/Encryption. Feel free to grab it and modify as you will. Better to store your KEY/SECRET encrypted in the registry rather than as plain text in your script or as environment variables.
I'm having some difficulty passing a list of strings to an API method using Powershell.
What I've tried:
What haven't I tried? My latest incarnation is this:
$uri = "http://localhost:15207/v1/API/GetFoos"
Add-Type -AssemblyName System.Core
$contents = New-Object System.Collections.Generic.List[string]
$contents.Add('Foo_1')
$contents.Add('Foo_1000002')
$body = #{
"someParam"="string1"
"contents"= $contents
}
Invoke-RestMethod -uri $uri -Body $body -Method Post
This results in the following value being received by the API:
[0] = "Foo_1 Foo_1000002"
But I've tried arrays, and all sorts of different combinations of parenthesis, brackets, single quotes, and double quotes. In all cases, the contents parameter either receives an object type, or a single value that is the concatenated combination of the values I'm trying to pass across.
I'm sure I'm not the first person having to pass a list of strings to an API method, but searching for this includes a lot of common terms resulting in unrelated matches.
Instead of Invoke-RestMethod, take a look at Invoke-WebRequest instead. Maybe something like this would work:
$uri = "http://localhost:15207/v1/API/GetFoos"
$body = #{}
$body.someParam = 'string1'
$body.contents = ('Foo1', 'Foo_1000002')
$requestJson = $body | ConvertTo_Json
$response = Invoke-WebRequest -uri $uri -Body $requestJson -ContentType "application/json" -Method Post
#Need to convert the JSON content into something we can use
$responseObject = $response.Content | ConvertFrom-Json