0

使用 powershell v2 和pushbullet,我尝试在修改文件时发送推送通知

$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

检查脚本outlog.txt是否写入了文件,但只写入了前两条消息,并且从未提交过通知。

当我uploadstring手动启动时

$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)

工作正常。

4

2 回答 2

0

在事件处理程序中对 $webclient.UploadString(...) 的调用会引发异常,这会终止它正在运行的 EventJob 上下文。您可以通过键入以下内容来验证这一点:

Get-Job 

并寻找失败的工作。然后,您可以对失败的作业执行 Recieve-Job 以获取错误消息。它可能是身份验证错误。通过放置一个有效的身份验证令牌,我能够让您的代码正常工作。

如果您想让事件处理程序在发生错误的情况下继续,您将不得不使用 try/catch,例如:

$result = try { $webclient.UploadString($url, "POST", $data) } 
          catch { $_.Exception.InnerException.Response }
于 2014-07-15T17:25:03.867 回答
0

全局变量$url在您的事件处理程序脚本块中不可用。像这样更改您的 Register-ObjectEvent :

$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -MessageData $url -Action {
    $name = $Event.SourceEventArgs.Name
    $path = $Event.SourceEventArgs.FullPath
    $url  = $Event.MessageData
    ...
}
于 2014-07-11T03:09:14.687 回答