powershell : ftp directory listing (help on a script)
I am trying to do a list view of a ftp directory. The viewing part is ok so far but I am unable to manipulate the data I am getting back. Here is the script that I used;
[System.Net.FtpWebRequest]$ftp = [System.Net.WebRequest]::Create("ftp://ftp.microsoft.com/ResKit/y2kfix/alpha/")
$ftp.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory #Details
$response = $ftp.getresponse()
$stream = $response.getresponsestream()
$buffer = new-object System.Byte[] 1024
$encoding = new-object System.Text.AsciiEncoding
$outputBuffer = ""
$foundMore = $fal开发者_如何学编程se
## Read all the data available from the stream, writing it to the
## output buffer when done.
do
{
## Allow data to buffer for a bit
start-sleep -m 1000
## Read what data is available
$foundmore = $false
$stream.ReadTimeout = 1000
do
{
try
{
$read = $stream.Read($buffer, 0, 1024)
if($read -gt 0)
{
$foundmore = $true
$outputBuffer += ($encoding.GetString($buffer, 0, $read))
}
} catch { $foundMore = $false; $read = 0 }
} while($read -gt 0)
} while($foundmore)
$outputBuffer
Here is the response I am geting back for this script;
PS C:\Users\Toshiba> C:\Apps\@PowerShell\FTPListDirectory.ps1
forfiles.exe
logtime.exe
timeserv
w32time
From there, how I can work on the data I am getting back. the file info (name, creation time, last update, etc.) and the other stuff.
My goal here is to view all the ftp data in a directory and then I can download all the files in a directory.
Any chance?
First you should retrieve all the data
Replace the method with this
$ftp.Method = [System.Net.WebRequestMethods+FTP]::ListDirectoryDetails
Without the details you only get the filenames.
To download a file I usually use the webclient class
$webclient = New-Object System.Net.WebClient
$webclient.credentials = New-Object System.Net.NetworkCredential("anonymous","anonymous@test.com")
$webclient.downloadfile("ftp://ftp.host.com/file.txt", "c:\temp\file.txt")
Downloadfile method of the webclient class
精彩评论