[Powershell] FTP Download File

 1 # Config
 2 $today = Get-Date -UFormat "%Y%m%d"
 3 $LogFilePath = "d:\ftpLog_$today.txt"
 4 $UserName = "ftpuser"
 5 $Password = "Password01!"
 6 
 7 
 8 function REM($Msg){
 9     $now= Get-Date
10     write-host "$now : $Msg" -foregroundcolor Yellow
11     Add-Content $LogFilePath "$now : $Msg"
12 }
13 
14 function DownloadFile($Username,$Password,$RemoteFile,$LocalFile){
15 
16     try
17     {
18         $ErrorActionPreference="Stop";
19 
20         if($RemoteFile -eq $null){ 
21             REM "RemoteFile is null"
22             return 
23         }
24         if($LocalFile -eq $null){ 
25             REM "LocalFile is null"
26             return 
27         }
28     
29         $FTPRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
30         $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username,$Password) 
31         $FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile 
32         $FTPRequest.UseBinary = $true
33         $FTPRequest.KeepAlive = $false
34         # Send the ftp request
35         $FTPResponse = $FTPRequest.GetResponse() 
36         # Get a download stream from the server response 
37         $ResponseStream = $FTPResponse.GetResponseStream() 
38         # Create the target file on the local system and the download buffer 
39         $LocalFileFile = New-Object IO.FileStream ($LocalFile,[IO.FileMode]::Create) 
40         [byte[]]$ReadBuffer = New-Object byte[] 1024 
41         if($ResponseStream -eq $null){
42             return
43         }
44         # Loop through the download 
45         do { 
46             $ReadLength = $ResponseStream.Read($ReadBuffer,0,1024) 
47             $LocalFileFile.Write($ReadBuffer,0,$ReadLength) 
48         
49         } 
50         while ($ReadLength -ne 0)
51 
52         REM "$RemoteFile 下载成功。"
53     }
54     catch
55     {
56         REM("Exception Msg: $_")
57     }
58 
59 }
60 
61 
62 
63 DownloadFile $UserName $Password "ftp://192.168.1.103/frate.csv" "c:\downloads\frate.csv"
64 DownloadFile $UserName $Password "ftp://192.168.1.103/bcirfp.csv" "c:\downloads\bcirfp.csv" 

连接Linux机器上的ftp时候,切记文件名是区分大小写滴!

转载于:https://www.cnblogs.com/wpsl5168/p/3196990.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值