2

In active batch, I have a report that runs using a Powershell script. The script looks like this:

$wc=new-object system.net.webclient -ErrorVariable err
$wc.UseDefaultCredentials = $true
$url = "http://SSRS-SERVER/etc...&rs:Command=Render&rs:Format=EXCEL"
$file = "ReportName.xls"
echo $url
echo $file
$wc.downloadfile($url,$file)
$err.count
$err 

This script runs perfectly fine when it's quicker than 1 min and 40 seconds, which I've read the default timeout for webclient is 100 - so that makes sense.

I've tried adding:

$wc.Timeout = 500

But no luck. It says:

Property 'Timeout' cannot be found on this object; make sure it exists and is settable.

Can someone please let me know how to extend the timeout period on this script?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jay
  • 455
  • 3
  • 17
  • 34
  • Based on what I'm seeing here - http://stackoverflow.com/questions/1789627/how-to-change-the-timeout-on-a-net-webclient-object it looks like you need to extend the class in order to make this work with the webclient. which is likely possible in PSv5 but I have not worked with the new powershell classes enough yet to know for sure that it woudl work. hwoever it does look like the System.Net.HttpWebRequest class has the timeout value you are looking for, however that class is deprecated and MS does not support using it directly... – Mike Garuccio Nov 04 '16 at 20:43
  • http://stackoverflow.com/questions/1789627/how-to-change-the-timeout-on-a-net-webclient-object – Hackerman Nov 04 '16 at 20:43

2 Answers2

3

If you're using Powershell 3.0 or higher, you can use Invoke-WebRequest and set the timeout

Invoke-WebRequest $url -UseDefaultCredentials -OutFile ReportName.xls -TimeoutSec 500
Alex
  • 511
  • 3
  • 12
  • Thanks for the info, unfortunately I'm not on that version. My company is stuck on 2.0 – Jay Nov 07 '16 at 19:19
1

You can extend the C# class in powershell to expose the timeout property.

$Source = @" 
using System.Net;

public class ExtendedWebClient : WebClient { 
    public int Timeout;

    protected override WebRequest GetWebRequest(System.Uri address) { 
        WebRequest request = base.GetWebRequest(address); 
        if (request != null) {
            request.Timeout = Timeout;
        }
        return request;
    }

    public ExtendedWebClient() {
        Timeout = 100000; // Timeout value by default 
    } 
} 
"@;

Add-Type -TypeDefinition $Source -Language CSharp

$webClient = New-Object ExtendedWebClient; 
# Change timeout for webClient 
$webClient.Timeout = 1800000; // milliseconds
$loadData = $webClient.downloadString('http://your_url')

Credit to: Mikhail Kozlov

Josh Noe
  • 2,664
  • 2
  • 35
  • 37