Posted in
Windows Powershell |
No Comment | 5,894 views | 04/08/2012 20:52
You can download a file from FTP and you can use “foreach” to process every line of the file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| # FTP Config
$FTPHost = "10.10.10.5"
$Username = "admin"
$Password = "12345678"
$FTPFile = "log/test.log"
# FTP Log File Url
$FTPFileUrl = "ftp://" + $FTPHost + "/" + $FTPFile
# Create FTP Connection
$FTPRequest = [System.Net.FtpWebRequest]::Create("$FTPFileUrl")
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UsePassive = $false
$FTPRequest.UseBinary = $true
$FTPRequest.KeepAlive = $false
# Get FTP File
$FTPResponse = $FTPRequest.GetResponse()
$ResponseStream = $FTPResponse.GetResponseStream()
$FTPReader = New-Object System.IO.Streamreader -ArgumentList $ResponseStream
do
{
Write-Host $FTPReader.ReadLine()
}
while ($FTPReader.ReadLine() -ne $null)
$FTPReader.Close()
} |
# FTP Config
$FTPHost = "10.10.10.5"
$Username = "admin"
$Password = "12345678"
$FTPFile = "log/test.log"
# FTP Log File Url
$FTPFileUrl = "ftp://" + $FTPHost + "/" + $FTPFile
# Create FTP Connection
$FTPRequest = [System.Net.FtpWebRequest]::Create("$FTPFileUrl")
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$FTPRequest.UsePassive = $false
$FTPRequest.UseBinary = $true
$FTPRequest.KeepAlive = $false
# Get FTP File
$FTPResponse = $FTPRequest.GetResponse()
$ResponseStream = $FTPResponse.GetResponseStream()
$FTPReader = New-Object System.IO.Streamreader -ArgumentList $ResponseStream
do
{
Write-Host $FTPReader.ReadLine()
}
while ($FTPReader.ReadLine() -ne $null)
$FTPReader.Close()
}
I used “do-while” to output each line of file.