Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2009-10-19
If you want to try this out, please read this first. There, I did an upload using FTP with network credentials (username and password). This time, I want to show how to download a file using HTTP. I am using PowerShell 2.0.
#Load the System.Net namespace. [System.Reflection.Assembly]::Load ("System.Net, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") #Load the System.IO namespace. [System.Reflection.Assembly]::Load ("System.IO, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a") #The target filename on the local system. $Target = "C:\downloaded.wav" #Full source path. $RemoteSource = "http://www.mysite.com/myfile.wav" #Use the static method Create to create a web request. #Pass the destination as an argument, and cast it to a HttpWebRequest. $R=[System.Net.HttpWebRequest][System.Net.WebRequest]::Create($RemoteSource) #If not anonymous requests are allowed, you can #add a System.Net.NetworkCredential to the Credentials #property of the request object ($R). #What kind of method it will represent? A http request. $R.Method = "GET" #Execute and grab the response object (System.Net.WebResponse). $Resp = $R.GetResponse() #Get a reference to the response stream (System.IO.Stream). $RespStream = $Resp.GetResponseStream() #Create a stream to write to the file system. $Wrt = [System.IO.File]::Create($Target) #Create the buffer for copying data. $Buffer = New-Object Byte[] 1024 #In an iteration... Do { #...attemt to read one kilobyte of data from the web response stream. $BytesRead = $RespStream.Read($Buffer, 0, $Buffer.Length) #Write the just-read bytes to the target file. $Wrt.Write($Buffer, 0, $BytesRead) #Iterate while there's still data on the web response stream. } While ($BytesRead -gt 0) #Close the stream. $RespStream.Close() $RespStream.Dispose() #Flush and close the writer. $Wrt.Flush() $Wrt.Close() $Wrt.Dispose()
Happy coding!
Categories: PowerShell
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply