我一直在寻找一种方法来了解我的ftp文件的状态,很少有日志文件在每15分钟后上传到我的ftp服务器上,但有几次上传失败,我只想在文件上传失败时发出警报。以下代码已经厌倦
function update {
$ftprequest = [System.Net.FtpWebRequest]::Create("ftp://ftpsite.com/Script_Apps/install_firefox.exe")
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::GetDateTimestamp
$response = $ftprequest.GetResponse().StatusDescription
$tokens = $response.Split(" ")
$code = $tokens[0]
$localfile = (Get-Item "$dirAppsinstall_firefox.exe").LastWriteTimeUtc
if ($tokens -gt $localfile) {
write-host "Updating Firefox Installer..."
$File = "$dirAppsinstall_firefox.exe"
$ftp = "ftp://ftpsite.com/Script_Apps/install_firefox.exe"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
$webclient.DownloadFile($uri, $File)
"Updated Firefox" >> $global:logfile
mainmenu
}
else {
Write-Host "Local Copy is Newer."
sleep 3
mainmenu
}
}
我假设这一行处理FTP站点的下载/上传文件。
$ftp = "ftp://ftpsite.com/Script_Apps/install_firefox.exe"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
$webclient.DownloadFile($uri, $File)
如果是这样,那么我们可以查找错误,并在try{}catch{}
块出现错误时采取措施。
您可以将任何代码放入try
块中,当它遇到终止错误时,它会将错误捕获为$Error[0]
,我们可以在catch
块中引用它。
try{
$ftp = "ftp://ftpsite.com/Script_Apps/install_firefox.exe"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
$webclient.DownloadFile($uri, $File)
}
catch{
#Write out an error to the screen
"failed to download file $($ftp). `n--Ran into error $($Error[0].Exception.Message)"
#Todo - send a notification
}
当它无法下载时,会出现这样的结果。
Failed to download file ftp://ftpsite.com/Script_Apps/install_firefox.exe.
---Ran into error Exception calling "DownloadFile" with "2" argument(s):
"Unable to connect to the remote server"
然后,您可以确定发送通知的最佳方式,以满足您的需求。有一种方法可以从PowerShell或推特发送电子邮件,甚至使用推送消息发送到手机上的Pushbullet应用程序!