问题描述
所以我有一个简单的 FTP 上传脚本,它循环上传一组文件。循环选择一个文件(排序的 gci 数组)上传它,然后移动到下一个。总共约20个文件。当我从服务器收到错误或从服务器确认上传已完成时,单个文件的循环结束。
最近,该服务器没有给我任何信息,允许上传通过,但没有确认文件已完成。基本上意味着脚本会在该循环中停留数小时,直到我手动关闭脚本。
我希望在主上传命令上设置超时:
$rs = $ftp.GetRequestStream()
$rs.Write($content,$content.Length)
看起来好像 write 命令,虽然文件完全写入目标 FTP 服务器,但永远不会从 FTP 服务器得到响应,这意味着它只会挂起,挂起,挂起。
我希望做的是添加超时。这里的挑战是,我不知道有什么方法可以在执行“写入”作业的过程中检查计时器。
我可以在这里选择吗?
这是我要做的,但似乎(我的猜测)因为在写入作业的中间从来没有将计时器相互比较,循环不会退出,直到 re.write
作业完成(可能永远不会)
这里有什么想法吗?
$timeout = New-TimeSpan -Seconds 8
$timer = [System.Diagnostics.Stopwatch]::StartNew()
do {
# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create($ftpdestination)
$ftp = [System.Net.FtpWebRequest]$ftp
# build authentication and connection
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential($username,$password)
$ftp.UseBinary = $true
$ftp.UsePassive = $true
$ftp.timeout = -1
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes($sourcefile)
$ftp.ContentLength = $content.Length
# get the request stream,and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content,$content.Length)
$rs.Close()
$rs.dispose()
}
while ($timer.Elapsed -lt $timeout)
所以这就是我正在使用的,但是,我发现问题在于在 rs.write
(我所有的时间都在那里)期间,它没有重新评估 ($timer.Elapsed -lt $timeout
) 方程,所以它不是停止。这就是我被卡住的地方。
解决方法
您的问题是 $ftp.timeout = -1
。 -1
表示“无限”。见the Remarks section in FtpWebRequest.Timeout
property documentation
将其设置为一些合理的值。