透過 PowerShell FTP 下載某個目錄內的檔案

朋友的需求

FTP 利用了 .NET 產生了自我簽章的憑證,要求 FTP 存取時需啟動 SSL

image

#讀取定義設定
param(
[string]$Username = “SQL2014\a",
[string]$Password = “P@ssw0rd1234″,
[string]$folderPath="ftp://localhost/",
[string]$target = “c:\temp\ftp\",
[string]$ErrorLogFile="c:\temp\ftp\errorlog.txt",
[bool]$logDetail=$true, #是否要存 Exception 的細節
[bool]$ssl=$true
)

function Get-FtpDir ($url,$credentials,[bool]$ssl) {
$request = [Net.WebRequest]::Create($url)
if($ssl)
{
#不信任根憑證也強制下載
[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$request.EnableSsl = $True #ftp 可以啟動 SSL
}
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
if ($credentials) { $request.Credentials = $credentials }
$response = $request.GetResponse()
$reader = New-Object IO.StreamReader $response.GetResponseStream()
$reader.ReadToEnd()
$reader.Close()
$response.Close()
}

$credential=new-object System.Net.NetworkCredential($Username, $Password)
$files=Get-FTPDir $folderPath $credential $ssl
$webclient = New-Object System.Net.WebClient
$webclient.Credentials =$credential
Foreach ($file in ($files.Split(“`r`n")  |  `

where {$_ -like “*.txt*"}))
{
$source=$folderPath+$file
$dest=$target+$file
try{
$WebClient.DownloadFile($source, $dest)
}
catch
{
$d=Get-Date
$sb= New-Object -TypeName “System.Text.StringBuilder"
[Void]$sb.Append(“***" + $source + “`t" + $d.ToString() + “`t" + $Message + “***" + “`r`n")
if($error -ne $null -and $logDetail)
{
foreach($err in $error)
{
if($err -ne $null){[Void]$sb.Append($err.ToString()+ “`r`n")}
if($err.Exception -ne $null){[Void]$sb.Append($err.Exception.ToString() + “`r`n")}
}
$error.Clear()
}
($sb.ToString() + “`r`n") | Out-File $ErrorLogFile -Append
Write-Host $sb.ToString() -ForegroundColor Red
}
}

發表迴響

在下方填入你的資料或按右方圖示以社群網站登入:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 變更 )

Twitter picture

You are commenting using your Twitter account. Log Out / 變更 )

Facebook照片

You are commenting using your Facebook account. Log Out / 變更 )

Google+ photo

You are commenting using your Google+ account. Log Out / 變更 )

連結到 %s

%d 位部落客按了讚: