Setup one timeout value for downloadstring method of WebClient Class in PowerShell


/ Published in: Windows PowerShell
Save to your folder(s)

Setup one timeout value for downloadstring method of WebClient Class in PowerShell

Property Timeout of WebClient isn't public, but we can inhertis from him and change this property in the new class

Inspired by: One article on What Was I Thinking? (http://goo.gl/IQQazD)
Thanks also to Stefan Goßner (http://goo.gl/T6RZJC)

run sample: powershell.exe -executionpolicy bypass .\DownloadString.ps1 100 "http://www.google.es"
run sample: powershell.exe -executionpolicy bypass .\DownloadString.ps1 -url "www.google.es" -timeout -1


Copy this code and paste it in your HTML
  1. # Setup one timeout value for downloadstring method of WebClient Class
  2. #
  3. # Property Timeout of WebClient isn't public, but we can inhertis from him and change this property in the new class
  4. #
  5. # Inspired by: One article on What Was I Thinking? (http://goo.gl/IQQazD)
  6. # Thanks also to Stefan Go�ner (http://goo.gl/T6RZJC)
  7. #
  8. # run sample: powershell.exe -executionpolicy bypass .\DownloadString.ps1 100 "http://www.google.es"
  9. # run sample: powershell.exe -executionpolicy bypass .\DownloadString.ps1 -url "http://www.google.es" -timeout -1
  10. Param(
  11. [string]$timeout, #input parameter (Download String Timeout).
  12. [string]$url #input parameter (url to Download).
  13. )
  14.  
  15.  
  16. $Source = @"
  17. using System.Net;
  18.  
  19. public class ExtendedWebClient : WebClient
  20. {
  21. public int Timeout;
  22.  
  23. protected override WebRequest GetWebRequest(System.Uri address)
  24. {
  25. WebRequest request = base.GetWebRequest(address);
  26. if (request != null)
  27. {
  28. request.Timeout = Timeout;
  29. }
  30. return request;
  31. }
  32.  
  33. public ExtendedWebClient()
  34. {
  35. Timeout = 100000; // the standard HTTP Request Timeout default
  36. }
  37. }
  38. "@;
  39.  
  40. Add-Type -TypeDefinition $Source -Language CSharp
  41.  
  42. $webclient = New-Object ExtendedWebClient;
  43. $webclient.Timeout=$timeout;
  44. $webclient.downloadstring($url);
  45. $webclient

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.