Difference between revisions of "Using Powershell for ftp 2"

From MyWiki
Jump to: navigation, search
 
Line 64: Line 64:
 
<source lang="powershell">
 
<source lang="powershell">
  
Function Get-FTPFiles{
 
  
[CmdLetBinding()]
 
Param(
 
[System.Uri]$uri='ftp://ftpsite/folder/subfolder/&#039;,
 
[string]$userid='username',
 
[string]$password='password'
 
)
 
 
$ftp=[system.net.ftpwebrequest]::Create($uri)
 
if($userid){$ftp.Credentials=New-Object System.Net.NetworkCredential($userid,$password)}
 
$ftp.Method=[system.net.webrequestmethods+ftp]::ListDirectoryDetails
 
$response=$ftp.GetResponse()
 
$strm=$response.GetResponseStream()
 
$reader=New-Object System.IO.StreamReader($strm,'UTF-8')
 
$list=$reader.ReadToEnd()
 
$list
 
$lines=$list.Split("`n")
 
foreach($line in $lines){
 
if($line){
 
$f=$line.Split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
 
$names = [string] "$($f[8]) $($f[9]) $($f[10]) $($f[11]) $($f[12]) $($f[13]) $($f[14])"
 
$dt=[datetime]"$($f[5]) $($f[6]) $($f[7])"
 
$length=$f[4]
 
$hash=@{Name=$names;FileDate=$dt;Length=$length;}
 
New-Object PSObject -Property $hash
 
}
 
 
foreach ($name in $names){
 
$name
 
$source = "$uri"+$name
 
$source
 
$target = '\\server\folder\subfolder\sub\sub2\'+$name
 
$target
 
$wc = new-object system.net.webclient
 
 
$uri2 = new-object system.uri($source)
 
 
#Download file from FTP server
 
Try{
 
#$wc.Credentials = new-object System.Net.NetworkCredential($userid, $password)
 
$wc.downloadfile($uri2, $target)
 
}
 
Catch [Net.WebException]{
 
$_|fl * -Force
 
}
 
#Delete files from FTP server after download
 
$request = [system.Net.FtpWebRequest]::Create($uri2)
 
$request.Method = [System.Net.WebRequestMethods+FTP]::DeleteFile
 
$response = $request.GetResponse()
 
"Deleted from FTP: $source" -f $response.StatusDescription
 
$response.Close()
 
}
 
}
 
}
 
 
Get-FTPFiles
 
  
  
 
</source>
 
</source>

Latest revision as of 12:24, 6 August 2015

$Server = "ftp://ftp.example.com/"
$User = "anonymous@example.com"
$Pass = "anonymous@anonymous.com"
 
Function Get-FtpDirectory($Directory) {
 
    # Credentials
    $FTPRequest = [System.Net.FtpWebRequest]::Create("$($Server)$($Directory)")
    $FTPRequest.Credentials = New-Object System.Net.NetworkCredential($User,$Pass)
    $FTPRequest.Method = [System.Net.WebRequestMethods+FTP]::ListDirectoryDetails
 
    # Don't want Binary, Keep Alive unecessary.
    $FTPRequest.UseBinary = $False
    $FTPRequest.KeepAlive = $False
 
    $FTPResponse = $FTPRequest.GetResponse()
    $ResponseStream = $FTPResponse.GetResponseStream()
 
    # Create a nice Array of the detailed directory listing
    $StreamReader = New-Object System.IO.Streamreader $ResponseStream
    $DirListing = (($StreamReader.ReadToEnd()) -split [Environment]::NewLine)
    $StreamReader.Close()
 
    # Remove first two elements ( . and .. ) and last element (\n)
    $DirListing = $DirListing[2..($DirListing.Length-2)] 
 
    # Close the FTP connection so only one is open at a time
    $FTPResponse.Close()
 
    # This array will hold the final result
    $FileTree = @()
 
    # Loop through the listings
    foreach ($CurLine in $DirListing) {
 
        # Split line into space separated array
        $LineTok = ($CurLine -split '\ +')
 
        # Get the filename (can even contain spaces)
        $CurFile = $LineTok[8..($LineTok.Length-1)]
 
        # Figure out if it's a directory. Super hax.
        $DirBool = $LineTok[0].StartsWith("d")
 
        # Determine what to do next (file or dir?)
        If ($DirBool) {
            # Recursively traverse sub-directories
            $FileTree += ,(Get-FtpDirectory "$($Directory)$($CurFile)/")
        } Else {
            # Add the output to the file tree
            $FileTree += ,"$($Directory)$($CurFile)"
        }
    }
 
    Return $FileTree
 
}