I have a problem with catching exception from NewWebServiceProxy cmdlet
try {
$myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc"
}
catch {
Write-Log ([string]::Format("Error : {0}", $_.Exception.Message))
}
When I run it i get this unhandled exception : New-WebServiceProxy :
The request failed with HTTP status 404: Not Found. At
C:\Users\SomeUser\AppData\Local\Temp\d052b604-38ad-4827-b952-4ebc66e79c69.ps1:2
char:18
+ $myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (http://localhost/someservice.svc:Uri) [New-WebServiceProxy], WebExc
eption
+ FullyQualifiedErrorId : WebException,Microsoft.PowerShell.Commands.NewWebServiceProxy
Somebody could ask me why try catch do not catch this exception ? Thanks for any aswer
This is one of the most common issues while catching an unhandled exception in powershell. You need to use -ErrorAction Stop in the command New-WebServiceProxy
try {
$myService = New-WebServiceProxy -Uri "http://localhost/someservice.svc" -ErrorAction Stop
}
catch [System.Net.WebException]{
Write-Log ([string]::Format("Error : {0}", $_.Exception.Message))
}
Updated: To catch Http exception include [System.Net.WebException] as noted by Keith Hill in the comment below.
What helped me was doing something more like
try{
New-WebServiceProxy -URI $webURL -ErrorAction Stop
}
catch [System.Net.WebException] {
return [PSCustomObject]#{
SOAPStatus = 'Failed'
SOAPException = $_.Exception.Message
SOAPInnerException = $_.Exception.InnerException.Message
}
}
catch {
return [PSCustomObject]#{
SOAPStatus = 'Failed'
SOAPError = $_.Exception.Message
}
}
By catching the inner exception I found I would get the web response as well if there was an issue with it. Which usually in these cases there was something like this for output:
SOAPStatus : Failed
SOAPException : There was an error downloading 'http://webserviceurl.com:1010/SystemServiceQuery'.
SOAPInnerException : The request failed with HTTP status 401: Unauthorized.
Of course you could then capture what type of innerexception and give more useful feedback to your users and such.
Related
I want to create an index pattern using the Opensearch API. The issue i'm having is with the message body type. I'm getting the following message when running my script
I'm running opensearch 1.3
Invoke-RestMethod: {"statusCode":400,"error":"Bad Request","message":"[request body.attributes]: expected value of type [object] but got [undefined]"}
$baseuri = "https://<clusterendpoint>.<region>.es.amazonaws.com"
#obtain auth cookie
$authbody = #"
{"username":"$apiUserName", "password":"$apiPassword"}
"#
$authUri = "$baseuri/_dashboards/auth/login"
Invoke-RestMethod -Method Post -Uri $authUri -Headers #{"osd-xsrf"="true"} -ContentType "application/json" -Body $authbody -SessionVariable S1
#### create index pattern
$indexid = "indexname"
$body=#"
{
"index_pattern": {
"title": "indexname-*",
"timeFieldName": "#timestamp"
}
}
"#
$uri = "$baseuri/_dashboards/api/saved_objects/index-pattern/$indexid"
Invoke-RestMethod -Method Post -Uri $uri -Headers #{"osd-xsrf"="true"} -ContentType "application/json" -WebSession $S1 -Body $body -Verbose
i've attempted various ways of defining an object with no luck. when I run the invoke with ($body | convertfrom-json) i get a different error message.
Invoke-RestMethod: {"statusCode":400,"error":"Bad Request","message":"[request body]: expected a plain object value, but found [null] instead."}
UPDATE: I did originally attempt to use the create index pattern API for elastic, but this results in a new index being created, not an opensearch index_pattern.
$body=#{
"index_pattern"= #{
"title"= "ai-summary"
}
}
$uri = "$baseuri/api/index_patterns/$indexid"
Invoke-RestMethod -Method Post -Uri $uri -Headers #{"osd-xsrf"="true"} -ContentType "application/json" -WebSession $S1 -Body ($body | ConvertTo-Json) -Verbose -Credential $credObject
Is there a REST API for getting the number of tests run/failed for a build?
I see there's one for getting Code Coverage but unless I am missing something obvious I can't find an API for just getting the number of tests run for a build.
Looks like that all APIs available to get Test Results require a test runid, but I only have a buildid.
You should try to use the Runs - Query API. Pass the optional build id.
GET https://dev.azure.com/{organization}/{project}/_apis/test/runs?minLastUpdatedDate={minLastUpdatedDate}&maxLastUpdatedDate={maxLastUpdatedDate}&buildIds={buildIds}&api-version=6.0
It's worth noting that you can customize the title of the run (with the build number included) by setting that on the task step of the pipeline.
I'm not sure if there is endpoint dedicated for tests but you can get tests from logs
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$(System.AccessToken)")) }
$uri = "https://dev.azure.com/$(devopsAccount)/$(projectName)/_apis/build/builds/$(Build.BuildId)/logs/$(logId)?api-version=5.1"
Write-Host $uri
# Invoke the REST call
$result = Invoke-RestMethod -Uri $uri -Method Get -Headers $AzureDevOpsAuthenicationHeader
Write-Host $result
$lines = $result.Split([Environment]::NewLine)
$passed = 0;
$failed = 0;
foreach($line in $lines) {
if ($line -match "Passed:.(\d+)") {
$passed = $matches[1]
}
if ($line -match "Failed:.(\d+)") {
$failed = $matches[1]
}
}
echo $passed
echo $failed
You need to pass your build id and log id. To get log id please get all logs and go trough them and find the one with your task with tests.
In terms of buildId vs runId, they are the same. I mean buildId = runId. With newer syntax there were a change in nomenclature.
You can use the Runs Query Api as Matt mentioned. However i found the buildId query parameter didnot work probably. You may need to filter the api results by the buildId. See below example:
$connectionToken="Personal Access Token"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$url = "https://dev.azure.com/{organization}/{project}/_apis/test/runs?minLastUpdatedDate=2020-10-20&maxLastUpdatedDate=2020-10-22&api-version=6.0"
$results= Invoke-RestMethod -Uri $trurl -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
$run = $results.value | Where-Object{$_.buildConfiguration.id -eq $buildId}
$runId = $run.id
You can also check out Runs List Api. I found the buildId was always appended to the run title. You can filter api results by the run name. See below:
$connectionToken="Personal Access Token"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$url = "https://dev.azure.com/{organization}/{project}/_apis/test/runs?api-version=6.0"
$results= Invoke-RestMethod -Uri $trurl -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
$run = $results.value | Where-Object{$_.name -match $buildId}
$runId = $run.id
I have a turtle file that I wish to send from S3 server to the Neptune instance on powershell. Below is the command I am using
Invoke-RestMethod -Uri http://edwardspoc.civwhymjvz19.us-east-1.neptune.amazonaws.com:8182 -ContentType application/json -body '
{
"source" : "s3://cedwardsneptune/ATC.ttl",
"format" : "turtle",
"iamRoleArn" : "arn:aws:s3:::cedwardsneptune",
"region" : "us-east-1",
"failOnError" : "FALSE",
"parserConfiguration" : {
"namedGraphUri" : "http://purl.bioontology.org/ontology/ATC"
}
}'
This is giving me the following error
Invoke-RestMethod : Cannot send a content-body with this verb-type.
I made subtle changes but nothing seems to be working. Any help is appreciated !
Error you having says that you are trying to send a BODY when your REQUEST VERB does not allow it.
Basically you are doing GET and trying to send a body. When GET verb is not allowed to send a body part.
Probably you need to use POST method (check specific webservice documentation)
For that I recommend you next format:
$Cred = Get-Credential (If you could have)
$Url = "http://edwardspoc.civwhymjvz19.us-east-1.neptune.amazonaws.com:8182"
$Body = '{
"source" : "s3://cedwardsneptune/ATC.ttl",
"format" : "turtle",
"iamRoleArn" : "arn:aws:s3:::cedwardsneptune",
"region" : "us-east-1",
"failOnError" : "FALSE",
"parserConfiguration" : {
"namedGraphUri" : "http://purl.bioontology.org/ontology/ATC"
}
}'
Invoke-RestMethod -Method 'Post' -Uri $url -Credential $Cred -ContentType $contentType -Body $body -ContentType 'application/json' -OutFile output.csv
(*)Of course -OutFile is optional
And about JSON There is a cmdlet called ConvertFrom-JSON you can use commonly when you need to parse an output(that is a JSON).
p.e:
Invoke-RestMethod -Method 'Post' -Uri $url -Credential $Cred -Body $body |
ConvertFrom-JSON | Select field1, field2, field3
If you expect an output (json) having field1, field2, field3 as fields
I'm executing the following:
Set-AzureRmVMExtension `
-VMName 'servername' `
-ResourceGroupName 'rgname' `
-Name 'JoinAD' `
-ExtensionType 'JsonADDomainExtension' `
-Publisher 'Microsoft.Compute' `
-TypeHandlerVersion '1.0' `
-Location 'West Europe' `
-Settings #{'Name' = 'domain.com'; 'OUPath' = 'OU=Server 2012 R2,OU=Servers,DC=domain,DC=com'; 'User' = 'domain.com\username'; 'Restart' = 'true'; 'Options' = 3} `
-ProtectedSettings #{'Password' = 'password'}
and get this error:
Set-AzureRmVMExtension : Long running operation failed with status
'Failed'. StartTime: 18.04.2016 18:03:30 EndTime: 18.04.2016 18:04:50
OperationID: 76825458-6c50-404d-bb1a-b27c722b1760 Status: Failed
ErrorCode: VMExtensionProvisioningError ErrorMessage: VM has reported
a failure when processing extension 'JoinAD'. Error message: "Join
completed for Domain 'ddomain.com'". At line:1 char:1
+ Set-AzureRmVMExtension `
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [Set-AzureRmVMExtension], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.Azure.Commands.Compute.SetAzureVMExtensionCommand
What am I missing?
Kept having trouble with extension, therefore opted to perform the domain join using PowerShell Add-Computer without extensions.
One possibly cause might be that NSG configurations block connectivity to the internet and with that to services running in the Azure data center.
I use WebRequest in a script powershell for check url is valid and detect webservice is available.
My script WebRequest
$request = [System.Net.WebRequest]::Create($WebServiceSSRSRDL)
$request.Method = 'HEAD'
$request.Credentials = [System.Net.CredentialCache]::DefaultCredentials
if ($request.Proxy -ne $null)
{
$request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}
$response = $request.GetResponse()
$httpStatus = $response.StatusCode
$urlIsValid = ($httpStatus -eq 'OK')
$tryError = $null
$response.Close()
But I get the error The remote server returned an error: (500) Internal Server Error.
If I use WebClient I get not error, all is OK.
My script WebClient
$webclient = New-Object Net.WebClient
$webclient.Credentials = [System.Net.CredentialCache]::DefaultCredentials
if($webclient.Proxy -ne $null)
{
$webclient.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}
$webclient.DownloadString($WebServiceSSRSRDL) | Out-Null
I would like use WebRequest in my script. Any suggestions about it ?