Powershell download file not working properly
I am trying to write a powershell script that will set a download directory variable based on the current directory, and download a file to that directory.
The code I have is:
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,$f开发者_运维知识库ile)
The problem I get is whenever I get to this part of the code it pumps out:
Exception calling "DownloadFile" with "2" argument(s): "An exception occurred during a WebClient request." At C:\directory\script.ps1:462 char:20
- $clnt.DownloadFile <<<< ($url,$file)
- CategoryInfo : NotSpecified: (:) [], MethodInvocationException
- FullyQualifiedErrorId : DotNetMethodException
Could anyone please help me figure out why this is happening?
$DevDownloadDirectory = [IO.Directory]::GetCurrentDirectory
Should be
$DevDownloadDirectory = [IO.Directory]::GetCurrentDirectory()
GetCurrentDirectory() is a Method and if you dont use the "()", it will just return the same name but not the current directory.
#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()
}
精彩评论