9/1/11

Powershell Asynchronous Download String

WebClient DownloadStringAsync
Powershell Register-ObjectEvent
PSEventArgs Properties
# - get webclient
$webClient = new-object net.webclient

# - register event handler for DownloadStringCompleted event
#   action script block is event handler code, show string DownloadStringCompletedEventArgs.Result
register-objectEvent $webClient downloadStringCompleted e1 {write-host $args[1].result}  #positional input params

# - begin asynchronous download string
#   event handlers will execute when download is complete
$webClient.downloadStringAsync("http://www.expressionsoftware.com")

# - list event subscriptions
get-eventSubscriber  #output #SubscriptionId  : 1
                             #SourceObject    : System.Net.WebClient
                             #EventName       : downloadStringCompleted
                             #SourceIdentifier: e1
                             #Action          : System.Management.Automation.PSEventJob
                             #SupportEvent    : False
                             #ForwardEvent    : False
                             #HandlerDelegate :

# - list jobs
get-job | fl  #output  #Id           : 1
                       #Name         : e1
                       #Command      : write-host $args[1].result
                       #State        : Running
                       #JobStateInfo : Running
                       #HasMoreData  : True
                       #Finished     : System.Threading.ManualResetEvent
                       #InstanceId   : 010f31f4-e8d2-4742-a782-79057faefebf
                       #Module       : __DynamicModule_a48149c1-5a56-4172-bc68-473ec7c83119
                       #StatusMessage:   #Location
                       #ChildJobs    : {}  #Output, Error, Progress, Verbose, Debug, Warning

# - register another handler, multiple event handlers supported, named input params
register-objectEvent -inputObject $webClient `
                     -eventName downloadStringCompleted `
                     -sourceIdentifier e2 `
                     -action {write-host ("async event at {0}`nevent handler source identifier: {1}`n{2}" -f ($event.timeGenerated.tostring("HH:mm:ss")), $event.sourceIdentifier, $args[1].result)}

# - unregister events
unregister-event -subscriptionId 1
unregister-event -sourceIdentifier e2
get-eventsubscriber -force | unregister-event -force  #unregister all events

# - synchronous download string
$webClient.downloadString("http://www.expressionsoftware.com")

Powershell asynchronous download file with WebClient DownloadFileAsync