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時候,切記文件名是區分大小寫滴!oop