$uri="http:\\www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing}
In above powershell script, how can I exit from Invoke-WebRequest if it takes time more than 10 secs, and return a error code if possible.
You can use the Timeout parameter to the Invoke-WebRequest command,
$uri="http://www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10}
You can cover it with try / catch block to get the error message.
try {
$uri="http://www.SomeUrl.com"
Measure-Command { $request = Invoke-WebRequest -Uri $uri -UseBasicParsing -Timeout 10 -ErrorAction Stop}
}
catch {
Write-Output "Timeout occured. Exception: $_"
}
You can also use -Headers #{"Cache-Control"="no-cache"} with Invoke-WebRequest which will not cache the pages you are visiting.
Related
I found that a site that I wanted to parse was down today when I went there to download a file.
The code I ran is:
$url = "https://notepad-plus-plus.org/downloads"
$page = Invoke-WebRequest -uri $url -UseBasicParsing
How can I intercept and handle this?
Is there a way to gracefully time out my request after 2 seconds if it does not get a response (which could be from the site being down or from my own internet having problems)?
What might be the best way to detect if what was returned is "connection timeout junk" as opposed to useful data that I can work with?
$url = "https://notepad-plus-plus.org/downloads" # Final url will be like: # https://github.com/notepad-plus-plus/notepad-plus-plus/releases/download/v8.4.6/npp.8.4.6.portable.x64.zip
try {
$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3
}
catch {
if ($_.Exception.Response.StatusCode -band 522) { "bad!"}
}
You should just call the current default error variable exception message/detail.
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop}
catch {$Error[0].Exception}
# Results
<#
The operation has timed out.
#>
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -ErrorAction Stop}
catch {$Error[0].Exception}
# Results
<#
The remote server returned an error: (522).
#>
Thus do what you want based on that error message.
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -ErrorAction Stop}
catch
{
If (($Error[0].Exception) -match '522')
{Write-Warning -Message 'Bad stuff happened. Now, go do stuff'}
}
# Results
<#
WARNING: Bad stuff happened. Now, go do stuff
#>
Update
Timeout check.
$timer = [Diagnostics.Stopwatch]::StartNew()
$url = "https://notepad-plus-plus.org/downloads"
try {$page = Invoke-WebRequest -uri $url -UseBasicParsing -TimeoutSec 3 -ErrorAction Stop}
catch
{
$Error[0].Exception
If (($Error[0].Exception) -match 'timed out')
{Write-Warning -Message 'Timeout occurred. Do you want to set a differnet timeout'}
}
$timer.Elapsed.TotalSeconds
# Results
<#
The operation has timed out.
WARNING: Timeout occurred. Do you want to set a differnet timeout
3.0225485
#>
what can i put in which can help me re run a failed release in azure devops?
$timer = New-TimeSpan -Minutes 120
while ($sw.elapsed -lt $timer) {
$ReleaseStatus = Invoke-RestMethod -Uri "https://vsrm.dev.azure.com/company/project/_apis/release/releases/$RId/environments/$EId/?`api-version=6.0" -Method GET -Headers $Header -Verbose
start-sleep -seconds 10
if ($ReleaseStatus.Status -eq 'Succeeded') {
write-host "Release Succeeded"
return
}
if ($ReleaseStatus.status -eq 'Rejected' -or 'active') {
Invoke-RestMethod "https://vsrm.dev.azure.com/company/project/_apis/release/releases?api-version=6.0" -Method POST -Headers $Header -Body $Body -Verbose
write-host "Error occured, Re-running Release"
return
}
}
i had to ping this endpoint in the end.
Invoke-RestMethod -Uri "vsrm.dev.azure.com/company/project/_apis/release/releases/$RId/…?`api-version=6.0" -Method GET -Headers $Header -Verbose
This allowed me to rerun the release instead of creating and running a new one in my script.
I need to produce some output when Invoke-WebRequest exceeds the time limit set by the -TimeoutSec parameter. How can I build an If condition that runs when this is the case?
In other words; what goes in place of ????? in the example below?:
Try {
Invoke-RestMethod -Uri $Uri -contentType "application/json"
-Method Post -Headers $Headers -Body $Body -TimeoutSec 8
}
Catch {
If (?????) {
Write-Host "the request timed out..."
}
}
In Windows PowerShell, the exception thrown will be a [System.Net.WebException] with the Status field set to Timeout:
try{
Invoke-WebRequest 'http://hostname.fqdn/really/slow/endpoint/' -TimeoutSec 3 -UseBasicParsing
}
catch [System.Net.WebException] {
if($_.Exception.Status -eq 'Timeout'){
# the request timed out
}
# something else went wrong during the web request
}
$x = Invoke-RestMethod -Method "Get" -uri $url -Headers $get_headers
**Start-Process "chrome.exe" $x.url**
Start-Sleep -s 10
Hello,
I am using the above to download a file via chrome. Is it possible to wait until the file download is complete to continue the script instead of sleeping or implementing an incremental retry function.
Thank you
So lets talk about what i see and ways to make it better
$x = Invoke-RestMethod -Method "Get" -uri $url -Headers $get_headers
Start-Process "chrome.exe" $x.url
Start-Sleep -s 10
Well you can save using the Invoke-RestMethod
Here is a example
Invoke-RestMethod "http://www.peoplelikeus.org/piccies/codpaste/codpaste-teachingpack.pdf" -OutFile "C:\codpaste-teachingpack.pdf"
In your case this might work.
$x = Invoke-RestMethod $url -Headers $get_headers
Invoke-RestMethod $x.url -OutFile "C:\SomeTypeOfFile.Txt"
The Invoke-RestMethod will wait until it is complete to move on in the code.
FYI (putting this here as it is too long for a normal comment), here are 3 other ways, that you could have done this:
$url = "http://mirror.internode.on.net/pub/test/10meg.test"
$output = "$PSScriptRoot\10meg.test"
$start_time = Get-Date
# 1. Invoke-WebRequest
Invoke-WebRequest -Uri $url -OutFile $output
"Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
# 2. System.Net.WebClient
(New-Object System.Net.WebClient).DownloadFile($url, $output)
"Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
# 3. Start-BitsTransfer
Start-BitsTransfer -Source $url -Destination $output -Asynchronous
"Time taken: $((Get-Date).Subtract($start_time).Seconds) second(s)"
I am new to powershell. I have a powershell script which basically makes an REST API request and gets back a JSON response. But I have an issue with the Invoke-RestMethod cmdlet. I mean the script sometimes doesn't wait for the response and continues with the next line of code.
Is there some trick in powershell which asks the code to wait for the API response and then run the remaining code. Below is my code
if ($EventID -eq '4726') {
$ad_user = "$TargetUsername#avayaaws.int"
$jsonbody = #{
"setupName" = "avayadev-or"
"instanceName" = "000_JumpServer_DMZ"
"command" = "$Command"
"parameters" = #{
"mobile" = "$getMobileAttr"
"ad_user"="$ad_user"
"label" ="$environment"
}
"eventToken" = "optional"
} | ConvertTo-Json
#$response = Start-Job {
# Invoke-RestMethod -Uri $uri -Method $verb -Body $jsonbody -Headers $header
#} | wait-job | receive-job
#$response = Invoke-RestMethod -Uri $uri -Method $verb -Body $jsonbody -Headers $header
$response = Invoke-WebRequest -Uri $uri -Method $verb -Body $jsonbody -Headers $header
$EventTrigger = $translEvent4726
Write-Output "Response is: $response"
PushLogs -transaction $EventTrigger -adUser $ad_user -transResult $response
}
I have tried many ways like using Out-Null and Wait-Job, Recieve-Job but couldn't get it to work. Any help is much appreciated.