powershell v2:WebClient/UploadString 从不连接 [英] powershell v2 : WebClient/UploadString never connect
本文介绍了powershell v2:WebClient/UploadString 从不连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 powershell v2 和 pushbullet,我尝试在修改文件时发送推送通知
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
为了检查脚本,outlog.txt
文件被写入,但只有前两条消息被写入并且通知从未被提交.
for check the script a outlog.txt
file is write, but only the two first messages are writen and the notification never is submitted.
当我手动启动 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)
工作正常.
推荐答案
全局变量 $url
在您的事件处理程序脚本块中不可用.像这样更改您的 Register-ObjectEvent:
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
...
}
这篇关于powershell v2:WebClient/UploadString 从不连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文