Powershell下载文件无法正常工作

时间:2010-11-14 04:14:00

标签: exception powershell download

我正在尝试编写一个powershell脚本,它将根据当前目录设置下载目录变量,并将文件下载到该目录。

我的代码是:

cd downloads
$DevDownloadDirectory = [IO.Directory]::GetCurrentDirectory

$clnt = New-Object System.Net.WebClient

# download and extract the file
$url = “fileurl/file.zip"
$file = "$DevDownloadDirectory\file.zip"
$clnt.DownloadFile($url,$file)

我得到的问题是每当我到达它抽出的这部分代码时:

  

使用“2”参数调用“DownloadFile”的异常:“异常   在WebClient请求期间发生。“在C:\ directory \ script.ps1:462   炭:20

     
      
  • $ clnt.DownloadFile<<<< ($网址,$文件)
  •   
  • CategoryInfo:NotSpecified:(:) [],MethodInvocationException
  •   
  • FullyQualifiedErrorId:DotNetMethodException
  •   

有谁可以帮我弄清楚为什么会这样?

2 个答案:

答案 0 :(得分:2)

$DevDownloadDirectory = [IO.Directory]::GetCurrentDirectory

应该是

$DevDownloadDirectory = [IO.Directory]::GetCurrentDirectory()

GetCurrentDirectory()是一个方法,如果您不使用“()”,它将只返回相同的名称,但不返回当前目录。

答案 1 :(得分:0)

#Dowload File
function Download-File-Func($url, $targetFile)
{
    "Downloading $url"
    $uri = New-Object "System.Uri" "$url"
    $request = [System.Net.HttpWebRequest]::Create($uri)
    $request.set_Timeout(600000) #10 minutes
    $response = $request.GetResponse()
    $totalLength = [System.Math]::Floor($response.get_ContentLength()/1024)
    $responseStream = $response.GetResponseStream()
    $targetStream = New-Object -TypeName System.IO.FileStream -ArgumentList $targetFile, Create
    $buffer = new-object byte[] 10KB
    $count = $responseStream.Read($buffer,0,$buffer.length)
    $downloadedBytes = $count
    while ($count -gt 0)
        {
        [System.Console]::CursorLeft = 0
        [System.Console]::Write("Downloaded {0}K of {1}K", [System.Math]::Floor($downloadedBytes/1024), $totalLength)
        $targetStream.Write($buffer, 0, $count)
        $count = $responseStream.Read($buffer,0,$buffer.length)
        $downloadedBytes = $downloadedBytes + $count
    }

    "Finished Download"
    $targetStream.Flush()
    $targetStream.Close()
    $targetStream.Dispose()
    $responseStream.Dispose()
}