powershell v2 : WebClient/UploadString never connect

青春壹個敷衍的年華 提交于 2019-12-11 21:22:29

问题


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.


回答1:


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
    ...
}



回答2:


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 }


来源:https://stackoverflow.com/questions/24683577/powershell-v2-webclient-uploadstring-never-connect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!