我想使用PowerShell自动化FTP下载数据库备份文件.文件名包含日期,因此我不能每天运行相同的FTP脚本.是否有一种干净的方法来构建PowerShell或使用.Net框架?
更新我忘了提到这是一个通过安全的FTP会话.
经过一些实验,我想出了这种方法来自动化PowerShell中的安全FTP下载.此脚本在Chilkat Software管理的公共测试FTP服务器上运行.因此,您可以复制并粘贴此代码,它将无需修改即可运行.
$sourceuri = "ftp://ftp.secureftp-test.com/hamlet.zip" $targetpath = "C:\hamlet.zip" $username = "test" $password = "test" # Create a FTPWebRequest object to handle the connection to the ftp server $ftprequest = [System.Net.FtpWebRequest]::create($sourceuri) # set the request's network credentials for an authenticated connection $ftprequest.Credentials = New-Object System.Net.NetworkCredential($username,$password) $ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile $ftprequest.UseBinary = $true $ftprequest.KeepAlive = $false # send the ftp request to the server $ftpresponse = $ftprequest.GetResponse() # get a download stream from the server response $responsestream = $ftpresponse.GetResponseStream() # create the target file on the local system and the download buffer $targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create) [byte[]]$readbuffer = New-Object byte[] 1024 # loop through the download stream and send the data to the target file do{ $readlength = $responsestream.Read($readbuffer,0,1024) $targetfile.Write($readbuffer,0,$readlength) } while ($readlength -ne 0) $targetfile.close()
我在这些链接上找到了很多有用的信息
FTP下载:编码问题
简单的FTP演示应用程序
非常简单的FTP客户端
如果要使用SSL连接,则需要添加该行
$ftprequest.EnableSsl = $true
在调用GetResponse()之前到脚本.有时您可能需要处理已过期的服务器安全证书(就像我不幸的那样).PowerShell代码存储库中有一个页面,其中包含一个代码片段.前28行与下载文件最相关.
取自这里
$source = "ftp://ftp.microsoft.com/ResKit/win2000/dureg.zip" $target = "c:\temp\dureg.zip" $WebClient = New-Object System.Net.WebClient $WebClient.DownloadFile($source, $target)
适合我