powershell v2:WebClient / UploadString从不连接

时间:2014-07-10 18:14:28

标签: powershell powershell-v2.0 webclient uploadstring

使用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)

工作正常。

2 个答案:

答案 0 :(得分: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
    ...
}

答案 1 :(得分:0)

在事件处理程序中调用$ webclient.UploadString(...)会抛出异常,从而终止它正在运行的EventJob上下文。您可以通过输入以下内容来验证:

Get-Job 

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

如果你想让事件处理程序继续,即使出现错误,你也必须使用try / catch,例如:

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