Question Get-Http

Plus d'informations
il y a 11 ans 10 mois #11797 par SiSMik
Get-Http a été créé par SiSMik
Bonjour,

le code ci-dessous permet de télécharger un fichier et d'afficher la progression dans un GUI et en commentaire le code pour l'afficher dans la console.

[code:1]function Get-HTTP {

<#
.SYNOPSIS
Download a web file

.DESCRIPTION
The 'Get-HTTP' function use .NET classes to download a file on a web server and print progressin the listbox.

.PARAMETER
String ones

.OUTPUTS
Returns error if problems, print logs in GUI and create a file.

.EXAMPLE
C:\PS>Get-HTTP -file http://127.0.0.1/Test/File.zip -target C:/Test/To/File.zip

#>


param ([String]$file,[String]$target)
$error.clear()

$R=[System.Net.HttpWebRequest][System.Net.WebRequest]::Create($file)
$R.Method = \"GET\"

if ($error) {
Write-Warning \"ERROR DOWNLOADING SCRIPT/SOURCE\"
exit 1
}

Try {
$Resp = $R.GetResponse()
[int]$goal = $Resp.ContentLength
$RespStream = $Resp.GetResponseStream()
$Wrt = [System.IO.File]::Create($Target)
$Buffer = New-Object Byte[] 1024

Do {
$BytesRead = $RespStream.Read($Buffer, 0, $Buffer.Length)
$Wrt.Write($Buffer, 0, $BytesRead)
if($goal -gt 0) {
$total += $BytesRead
$percent = [math]::round(($total/$goal)*100, 0)
$total_round = [math]::round($total/1024, 2)
$goal_round = [math]::round($goal/1024, 2)

# peu être supprimé
$listBox1.Items.RemoveAt($listBox1.Items.Count - 1)
$listBox1.Items.AddRange(\"Downloading $total_round KB of $goal_round KB. $percent% Done.\"«»)
#cls
#write-host \"$percent%\"
[System.Windows.Forms.Application]::«»DoEvents()
}
} While ($BytesRead -gt 0)

#Close the stream.
$RespStream.Close()
$RespStream.Dispose()

#Flush and close the writer.
$Wrt.Flush()
$Wrt.Close()
$Wrt.Dispose()
}
Catch {
$listBox1.Items.AddRange(\"Error Downloading Sources from HTTP Repository\"«»)
$listBox1.Items.AddRange(\"Check if the server is started\"«»)
exit 1
}
}[/code:1]

Exemple:
[code:1]
$http = \"http://127.0.0.1/File.zip\"
$dest_sources = \"c:\temp\file.zip\"
$timetotal = (Measure-Command { Invoke-Command -scriptblock { Get-HTTP $http $dest_sources } } ).TotalSeconds
$timetotal[/code:1]

Si vous n'avez (surement) pas de listbox, ou si vous utilisez un autre systeme d'affichage des pog/progression, bah changez les lignes qui comment par listbox1.

[code:1][System.Windows.Forms.Application]::«»DoEvents()[/code:1] sert à éviter que la fenetre parte en not responding pendant le while.

Voilà peut être que ça aidera certains...

@+<br><br>Message édité par: benduru, à: 14/05/12 14:24

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 11 ans 10 mois #11800 par Matthew BETTON
Réponse de Matthew BETTON sur le sujet Re:Get-Http
Salut benduru,

Bon... Je te joins le speech que Tome Tanasovski m'a fait lors des Scripting Games 2011, ici :

The real problem with your script is that you choose such a low level way of handling the http request. To be fair, I did compare your method with the System.Net.Webclient method of downloading the data and your way is a bit slower (.460 seconds compared to .249 seconds). If it was faster I would say that I understand your choice of classes, but there is a better way to do this.


J'avais du coup utilisé ce retour d'expérience dans ce script :

[code:1] Write-Debug \&quot;Downloading web page from $URI address ...\&quot;
try{
$WebClient = New-Object System.Net.WebClient
$output = $WebClient.DownloadString($URI)
}
catch{
Write-Error \&quot;An error has occured while downloading '$URI' web page\&quot;
}
[/code:1]

msdn.microsoft.com/en-us/library/system....nt%28v=vs.95%29.aspx

Merci pour ton script

@ +

Matthew<br><br>Message édité par: Matthew BETTON, à: 14/05/12 20:56

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 11 ans 10 mois #11801 par SiSMik
Réponse de SiSMik sur le sujet Re:Get-Http
Merci pour ton retour,
Le probème avec ta méthode c'est que faire un \&quot;write-progress\&quot; avec ta classe y'a pas de boucle.

ça va me demander plus de taff :D

:whistle:

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 11 ans 10 mois #11802 par Matthew BETTON
Réponse de Matthew BETTON sur le sujet Re:Get-Http
Une autre approche avec HTTWebRequest et Write-Progress pour afficher la progression.

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 11 ans 10 mois #11803 par Matthew BETTON
Réponse de Matthew BETTON sur le sujet Re:Get-Http
benduru écrit:

Merci pour ton retour,
Le probème avec ta méthode c'est que faire un \&quot;write-progress\&quot; avec ta classe y'a pas de boucle.

ça va me demander plus de taff :D

:whistle:


J'étais justement en train de regarder... En fait non, avec les events, c'est mêmes plus simple.

Un exemple :

[code:1]$client = New-Object System.Net.WebClient
$url = [uri]\&quot;ftpclubicb9a.clubic.com/files/ecc00ce73a...cais_10829.exe\";

try {

Register-ObjectEvent $client DownloadProgressChanged -action {

Write-Progress -Activity \&quot;Downloading\&quot; -Status (\&quot;{0} of {1}\&quot; -f $eventargs.BytesReceived, $eventargs.TotalBytesToReceive) -PercentComplete $eventargs.ProgressPercentage
}

Register-ObjectEvent $client DownloadFileCompleted -SourceIdentifier Finished

$file = \&quot;F:\Sources\vlc.exe\&quot;
$client.DownloadFileAsync($url, $file)

# optionally wait, but you can break out and it will still write progress
Wait-Event -SourceIdentifier Finished

} finally {
$client.dispose()
}[/code:1]

Connexion ou Créer un compte pour participer à la conversation.

Plus d'informations
il y a 11 ans 10 mois #11804 par Laurent Dardenne
Réponse de Laurent Dardenne sur le sujet Re:Get-Http
benduru écrit:

Le probème avec ta méthode c'est que faire un \&quot;write-progress\&quot; avec ta classe y'a pas de boucle.

Pas grave, propose nous une version avec un job :P
Comme ça on peut en lancer + par session :whistle:
benduru écrit:

ça va me demander plus de taff

Ou une occasion d'apprendre et de partager.

Tutoriels PowerShell

Connexion ou Créer un compte pour participer à la conversation.

Temps de génération de la page : 0.081 secondes
Propulsé par Kunena