Powershell FTP 脚本

Powershell FTP script

我正在循环使用此脚本从服务器下载大量文件,效果非常好。

$sourceuri = "ftp://ftp.secureftp-test.com/hamlet.zip"
$targetpath = "C:\hamlet.zip"
$username = "test"
$password = "test"

# Create a FTPWebRequest object to handle the connection to the ftp server
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)

# set the request's network credentials for an authenticated connection
$ftprequest.Credentials =
New-Object System.Net.NetworkCredential($username,$password)

$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false

# send the ftp request to the server
$ftpresponse = $ftprequest.GetResponse()

# get a download stream from the server response
$responsestream = $ftpresponse.GetResponseStream()

# create the target file on the local system and the download buffer
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024

# loop through the download stream and send the data to the target file
do{
    $readlength = $responsestream.Read($readbuffer,0,1024)
    $targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)

$targetfile.close()

但有时目标文件不存在,然后此脚本开始刷新我的命令提示符并显示错误。调试起来有点烦人,哪个文件丢失了。有没有办法在缺少文件时立即关闭此脚本并跳到下一个?

这里是错误:

Exception calling "GetResponse" with "0" argument(s): "The remote server returned a
n error: (550) File unavailable (e.g., file not found, no access)."
At D:\powershell\IPO_preveri_CMD_ALL\ftp.ps1:37 char:5
+     $ftpresponse = $ftprequest.GetResponse()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

You cannot call a method on a null-valued expression.
At D:\powershell\IPO_preveri_CMD_ALL\ftp.ps1:40 char:5
+     $responsestream = $ftpresponse.GetResponseStream()
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

然后重复最后 6 行...

听起来你只是在要求一个简单的 try-catch。我不知道 [System.Net.FtpWebRequest] 必须提供什么错误处理,所以这种通用方法是一个很好的起点。

$SavedErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "Stop" 

Try{
    # send the ftp request to the server
    $ftpresponse = $ftprequest.GetResponse()

    # get a download stream from the server response
    $responsestream = $ftpresponse.GetResponseStream()

    # create the target file on the local system and the download buffer
    $targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
    [byte[]]$readbuffer = New-Object byte[] 1024

    # loop through the download stream and send the data to the target file
    do{
        $readlength = $responsestream.Read($readbuffer,0,1024)
        $targetfile.Write($readbuffer,0,$readlength)
    }
    while ($readlength -ne 0)

    $targetfile.close()
} Catch {
    # Notify user an error occured. 
    Write-Warning "Unable to download '$sourceuri' because: $($_.exception)"
}

$ErrorActionPreference = $SavedErrorActionPreference 

所以如果任何终止错误发生在try块处理停止并执行catch块。从它的外观来看,这些错误并没有终止,所以我们需要暂时将其更改为 Stop 以确保 try 块正常运行。

然后在 catch 块中,我们采用 最简单 方法,只写出失败的文件路径,同时提供与错误相关的消息。使用上面的例子你应该得到类似的东西:

Unable to download 'ftp://ftp.secureftp-test.com/hamlet.zip' because: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

这应该在出现第一个错误时停止。通过停止处理,它将避免空表达式错误。