Question Get-Http
- SiSMik
- Auteur du sujet
- Hors Ligne
- Membre platinium
- Messages : 492
- Remerciements reçus 0
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.
- Matthew BETTON
- Hors Ligne
- Membre platinium
- Messages : 968
- Remerciements reçus 0
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 \"Downloading web page from $URI address ...\"
try{
$WebClient = New-Object System.Net.WebClient
$output = $WebClient.DownloadString($URI)
}
catch{
Write-Error \"An error has occured while downloading '$URI' web page\"
}
[/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.
- SiSMik
- Auteur du sujet
- Hors Ligne
- Membre platinium
- Messages : 492
- Remerciements reçus 0
Le probème avec ta méthode c'est que faire un \"write-progress\" avec ta classe y'a pas de boucle.
ça va me demander plus de taff
Connexion ou Créer un compte pour participer à la conversation.
- Matthew BETTON
- Hors Ligne
- Membre platinium
- Messages : 968
- Remerciements reçus 0
Connexion ou Créer un compte pour participer à la conversation.
- Matthew BETTON
- Hors Ligne
- Membre platinium
- Messages : 968
- Remerciements reçus 0
Merci pour ton retour,
Le probème avec ta méthode c'est que faire un \"write-progress\" avec ta classe y'a pas de boucle.
ça va me demander plus de taff
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]\"ftpclubicb9a.clubic.com/files/ecc00ce73a...cais_10829.exe\"
try {
Register-ObjectEvent $client DownloadProgressChanged -action {
Write-Progress -Activity \"Downloading\" -Status (\"{0} of {1}\" -f $eventargs.BytesReceived, $eventargs.TotalBytesToReceive) -PercentComplete $eventargs.ProgressPercentage
}
Register-ObjectEvent $client DownloadFileCompleted -SourceIdentifier Finished
$file = \"F:\Sources\vlc.exe\"
$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.
- Laurent Dardenne
- Hors Ligne
- Modérateur
- Messages : 6300
- Remerciements reçus 68
Pas grave, propose nous une version avec un jobLe probème avec ta méthode c'est que faire un \"write-progress\" avec ta classe y'a pas de boucle.
Comme ça on peut en lancer + par session
benduru écrit:
Ou une occasion d'apprendre et de partager.ça va me demander plus de taff
Tutoriels PowerShell
Connexion ou Créer un compte pour participer à la conversation.
- Vous êtes ici :
- Accueil
- forum
- PowerShell
- Contributions à la communauté
- Get-Http