JuanPablo
JuanPablo

Reputation: 24774

powershell v2 : WebClient/UploadString never connect

with powershell v2 and pushbullet, I try to send push notification when a file in modified

$folder = 'c:\path\to\file'
$filter = '*.*'
$user = "pushbullet_token"
$url = "https://api.pushbullet.com/v2/pushes"

$fsw = New-Object IO.FileSystemWatcher $folder, $filter
$fsw.IncludeSubdirectories = $true
$fsw.NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {

    $name = $Event.SourceEventArgs.Name
    $path = $Event.SourceEventArgs.FullPath

Out-File -FilePath c:\path\to\file\outlog.txt -Append -InputObject "$path"

    $title = $path
    Add-Type -AssemblyName System.Web
    $title = [System.Web.HttpUtility]::UrlEncode($title)
    $data =  "type=note&title=" + $title + "&body=body"

    $webclient = new-object System.Net.WebClient
    $webclient.Credentials = new-object System.Net.NetworkCredential($user, "")

Out-File -FilePath c:\path\to\file\outlog.txt -Append -InputObject "$data"

    $result = $webclient.UploadString($url, "POST", $data)

Out-File -FilePath c:\path\to\file\outlog.txt -Append -InputObject "$result"

}
#Unregister-Event FileCreated

for check the script a outlog.txt file is write, but only the two first messages are writen and the notification never is submitted.

when I launch uploadstring manually

$user = "pushbullet_token"
$url = "https://api.pushbullet.com/v2/pushes"
$data = "type=note&title=title&body=body"
$webclient = new-object System.Net.WebClient
$webclient.Credentials = new-object System.Net.NetworkCredential($user, "")
$result = $webclient.UploadString($url, "POST", $data)

work ok.

Upvotes: 0

Views: 2349

Answers (2)

Burt_Harris
Burt_Harris

Reputation: 6874

The call to $webclient.UploadString(...) in the event handler is throwing an exception, which terminates the EventJob context it's running in. You can verify this by typing:

Get-Job 

and looking for the failed job. You can then do Recieve-Job on the failed job to get the error message. Its probably an authentication error. By putting a valid authentication token, I was able to get your code to work.

If you want to have event handler continue even in the event of an error you'll have to use a try/catch, for example:

$result = try { $webclient.UploadString($url, "POST", $data) } 
          catch { $_.Exception.InnerException.Response }

Upvotes: 0

Keith Hill
Keith Hill

Reputation: 201682

The global variable $url is not available inside your event handler script block. Change your Register-ObjectEvent like so:

$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData $url -Action {
    $name = $Event.SourceEventArgs.Name
    $path = $Event.SourceEventArgs.FullPath
    $url  = $Event.MessageData
    ...
}

Upvotes: 0

Related Questions