Invoke SSRS Report in PowerShell and Register SSRS-Event Log Entry - powershell

Need: A PowerShell script to call an SSRS report (SSRS 2012) such that the web-call appears as a regular interactive request when viewed in SSRS's ExecutionLog3 (SSRS's log DB view).
Problem: I've tinkered around w/ the following script to try to figure out what parameters are necessary to force the SSRS server to log the call as if it was coming from a human/browser. This script works fine. I'm connected & getting a response for all 3 methods, but SSRS isn't logging it at all. Were I to invoke the same report in IE/Chrome manually - SSRS logs it accordingly & correctly.
I've used the F12 tools in Chrome to see if I can find, perhaps, some JS code that is actually doing the log-registration-req, alas - too advanced for me.
Thoughts?
# My AdventureWorks Sales Order Detail (.rpl) requires no parameters.
$RS1 = $null
$RS2 = $null
$RS3 = $null
# Try using the direct URL of the report approach
$Uri1 = 'http://reportstest.domain.com/home/report/AdventureWorks-Test/Sales%20Orders/Sales%20Order%20Detail.rdl'
# Try using the ReportViewer.aspx followed by path & variables approach
$Uri2 = 'http://reportstest.domain.com/Service/Pages/ReportViewer.aspx?%2fAdventureWorks-Test%2fSales+Orders%2fSales+Order+Detail&rc:Command=Render'
# Try using the Service approach
$Uri3 = 'http://reportstest.domain.com/Service?/AdventureWorks-Test%2fSales+Orders%2fSales+Order+Detail'
# Try each Uri to see if we create an entry in SSRS's ExecutionLog3
$RS1 = Invoke-WebRequest -Uri $Uri1 -UseDefaultCredentials -DisableKeepAlive
$RS2 = Invoke-WebRequest -Uri $Uri2 -UseDefaultCredentials -DisableKeepAlive
$RS3 = Invoke-WebRequest -Uri $Uri3 -UseDefaultCredentials -DisableKeepAlive
# See the response for each attempt, check for '200'
$RS1.StatusCode
$RS2.StatusCode
$RS3.StatusCode

Related

export complete TFS work item incl. history with PowerShell

I am working for a customer who is running a Dynamics AX project and is using TFS. I do have access to TFS and am able to check all the different work items - however, what I am missing is an overview to build metrics as the only way to get data into a table (Excel) does not allow me to get the history of a work item.
I am hence wondering how I could do this using PowerShell. I am completely new to this, accordingly step-by-step guidance would be highly appreciated.
You can use TFS Rest API.
For example:
$serverUrl = "http://tfsServer:8080/tfs/Collection"
$workItemId = "1"
#Get the Work Item
$workItem = Invoke-RestMethod -Uri "$($serverUrl)/_apis/wit/workitems/$($workItemId)?api-version=3.0" -UseDefaultCredentials -Method Get
#Print the revisions number
Write-Host $workItem.rev
#Get the specific revision details
$revision = Invoke-RestMethod -Uri "$($serverUrl)/_apis/wit/workitems/$($workItemId)/revisions/2?api-version=3.0" -UseDefaultCredentials -Method Get
#Print the Work Item details in the specific revision
Write-Host $revision.fields

What is the curl equivalent command in powershell for uploading the apk file?

I am trying to perform CI/CD using Perfecto and hence I am trying to upload a file to perfecto when my Bamboo build is finished.
I was trying with the following cURL command when we have a Linux server.
curl -X POST --upload-file test.apk 'https://****.perfectomobile.com/services/repositories/media/PRIVATE:test.apk?operation=upload&user=<email>&password=<password>&overwrite=true'
Now our server is changed to Windows and hence I want a powershell script which I can use as an Inline Scripts in Bamboo.
Can you please tell me what is an equivalent script in Powershell for windows.
Many thanks in advance.
# Gather your information.
$email = "myEmail#website.com";
$password = "powershellR0cks!";
$subDomain = "****";
$url = "https://$subDomain.perfectomobile.com/services/repositories/media/PRIVATE:test.apk?operation=upload&user=$email&password=$password&overwrite=true";
$filePath = ".\test.apk";
# Make the request.
$response = Invoke-WebRequest -Uri $URL -Method Post -InFile $filePath -ContentType "application/octet-stream";
# Check for success.
if (-not ($response.StatusCode -eq 200)) {
throw "There was an error uploading the APK manifest.";
}
You may want to check the value of -ContentType, but I think that's correct. You don't necessarily need to include the scheme (HTTPS) if you don't want to, and semicolons in PowerShell are optional, but you can include them if you want.
The $response variable is an HtmlWebResponseObject that has the content of the response, the status code, and a bunch of other useful info. You can check out the available properties and methods on the object by running $response | Get-Member.
Finally, the Invoke-WebRequest cmdlet also has other parameters that may be useful to you, such as -Credential, -Headers, and more.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-5.1
As a side-note, if you run Get-Alias -Name "curl", you can see that anytime you use curl in PowerShell, you're really just calling Invoke-WebRequest. You can use the curl alias if you want, but it's generally not a good idea to use aliases in automation since they can be modified or deleted.

How can I get the last test run id from TFS to my powershell script

I would like to use the very last TestRunId in case of create a report via powershell which sends the infos to Slack. I use Team Services REST API to get the test results. It works fine but only with specific Run ID. Here is a link where you can find good examples: enter link description here
I'm stuck at finding a way to get the last test result ID which I would use in my GET request to the TFS REST API:
Invoke-RestMethod -Uri "https://{instance}/DefaultCollection/{project}/_apis/test/runs/{run}/results?api-version={version}[&detailsToInclude={string}&$skip={int}&$top={int}]"
So I find {run} as the last Test Run ID with no luck.
Anyone have an idea? I cant find any query language which can be use in this situation in a powershell script.
You could retrieve the list of test runs, the sort descending the result on ID, since the most recent test run has the greatest ID. Then get the first item of the result. All of this shown below in powershell:
$username = "doesnotmatter"
$token = "PUTYOURTOKEN_HERE"
$instance = "PUTYOURACCOUNTHERE.visualstudio.com"
$teamProjectName = "PUTHEREYOUR_TEAM_PROJECT_NAME"
#create auth header to use for REST calls
$accessToken = ("{0}:{1}" -f $username,$token)
$accessToken = [System.Text.Encoding]::UTF8.GetBytes($accessToken)
$accessToken = [System.Convert]::ToBase64String($accessToken)
$headers = #{Authorization=("Basic {0}" -f $accessToken)}
$testRuns = Invoke-RestMethod -Uri "https://$instance/defaultcollection/$(teamProjectName)/_apis/test/runs/?api-version=3.0-preview" -Headers $headers -Method Get
$testRunsIdSorted = $testRuns.value | sort-object id -Descending
$mostRecentTestRun = Invoke-RestMethod -Uri "https://$instance/defaultcollection/$(teamProjectName)/_apis/test/runs/$($testRunsIdSorted[0].id)?api-version=3.0-preview" -Headers $headers -Method Get
$mostRecentTestRun is now the most recent test run.
Note that the script does no error checking at all.
Note that for authentication the script is using a Personal Access Token that needs to have the Test management (read) scope at least.

PowerShell Invoke-Webrequest not compatible with site?

I've seen many examples of Invoke-Webrequest and I've already had some success with it myself, however, one site where I was trying to automate my login just hasn't worked no matter what I try. Here is the code:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # This is required so that HTTPS requests won't fail with Invoke-WebRequest
$r = Invoke-WebRequest -Uri https://order.swisschalet.com -SessionVariable sc
$r.forms[0].fields['form-login-header-email'] = "MyEmail"
$r.forms[0].fields['form-login-header-password'] = 'MyPassword'
$a = Invoke-WebRequest -Uri ("https://order.swisschalet.com" + $r.forms[0].Action) -WebSession $sc -Method POST -Body $r.forms[0]
I have tried using Fiddler 4 to analyze what is going on but it has only confused me even more. When I manually go to the website Fiddler shows 'email' and 'password' fields that were posted rather than what originally came back in the forms which is 'form-login-header-email' and 'form-login-header-password'. However, even if I try to create these new fields and POST them it still doesn't work. Fiddler shows that going to the website manually also creates some kind of synchronization token called 'org.codehaus.groovy.grails.SYNCHRONIZER_TOKEN'.
I am beginning to wonder if Invoke-WebRequest is simply incompatible with this site as I can never get the expected response where I can find my name in the $a.parsedHTML.DocumentElement.InnerText. Instead, when I view this I simply get the full page back telling me that my session has already expired.
I started to try this with the IE Com Object as well but this also did not seem to work. Am I missing something or is it just the way this site has been made? I've been struggling with this (really just to learn) for a couple of days now.
Thanks for any help!
If you send what it sends, to the place it sends it, you get logged in:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # This is required so that HTTPS requests won't fail with Invoke-WebRequest
$r = Invoke-WebRequest -Uri https://order.swisschalet.com -SessionVariable sc
$form = #{
delegate='login'
id='null'
mode='save'
target='#form-login'
email='email#example.com'
password='password'
}
$a = Invoke-WebRequest -Uri "https://order.swisschalet.com/order/auth/index" -WebSession $sc -Method POST -Body $form
and it says
<span class="welcome-back">Welcome, <span class="username">TestingSome StuffForStackOverflo</span>
in the $a.RawContent result. So I guess it's not incompatible.

Powershell and NITRO API for Citrix NetScaler error on GET method

I am using a PowerShell module provided by Citrix to invoke the Nitro REST API. Calling the function I can successfully add and remove load balanced services from the load. However when I try to do a GET method to get the status of a service I get the error:
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
I have tried running Invoke-RestMethod without using the module but get the same error
Invoke-RestMethod -WebSession $myNSSession.WebSession -Method GET -Uri https://<NetScaler IP/nitro/v1/config/service/<Service Name>
When googling this error everything seems to point to certificate issues. I had this initially even on POST method until i added the below to my script
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
So since this works for doing POST i cant see why it wouldn't for a GET!!
another weird thing is, if I put the URL directly into the browser then enter my credentials i get a response in raw text! so it looks like this is an issue with the way i am calling it in PowerShell rather than the NetScaler or the NITRO API!
Someone please help as this is driving me crazy!!
Admitedly i am new to Invoke-RestMethod commands, but try this:
$creds = Get-Credential
$service = Invoke-RestMethod -Uri https://<NetScaler IP/nitro/v1/config/service/<Service Name> -Credential $creds
What you will get is something similar to this:
*errorcode* *message* *serverity* *service*
* 0 Done NONE {#{name=<service name; n..
then type $service.service and you will see more information. whatever attributes are availible will be listed. then just follow the pattern:
$service.service.
I had the same problem with Nitro API (specifically v10.5), and found that setting certificate policies, TLS versions and trust settings had no effect. POST works, GET fails.
The solution for me was to not use the cmdlets and instead drop back to a native .Net method. Below I am still using HTTPS with an internal certificate, hence still setting the callback.
$NSProtocol = "https://"
$NSHostname = "netscaler"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$WebRequest = [System.Net.WebRequest]::Create("$NsProtocol$NsHostname/nitro/v1/config/hanode")
$WebRequest.Method = "GET"
$WebRequest.ContentType = "application/json; charset=utf-8";
$WebRequest.Headers.Add("AUTHORIZATION","Basic $([System.Convert]::ToBase64String([System.Text.Encoding]::GetEncoding("ISO-8859-1").GetBytes($nsuser+":"+$nspass)))")
$Response = $WebRequest.GetResponse()
$ReadStream = New-Object System.IO.StreamReader $Response.GetResponseStream()
$HaState = ConvertFrom-Json $ReadStream.ReadToEnd()
Hope that helps.