PsWrite.psm1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 |
if ($JENKINS) { function Write-Host { <# .SYNOPSIS Wrapper for Write-Host, adds ANSI SGR codes based on -foregroundColor and -backgroundColor .DESCRIPTION Renplace le Write-host standard, pour une compatibilité avec les sorties linux (JENKINS)  .PARAMETER object Liste de String qui seront regroupe et affichée en couleur .PARAMETER foregroundColor Couleur du texte .PARAMETER backgroundColor Couleur de fond .PARAMETER nonewline si pas de retour a la ligne .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> param( $object, [ConsoleColor]$foregroundColor, [ConsoleColor]$backgroundColor, [switch]$nonewline ) if (!(Get-Command Write-HostOriginal -ea 0).name){ # doit etre embarque (pour les scriptblock) $global:ConsoleOutput = '' $metaData = New-Object System.Management.Automation.CommandMetaData (Get-Command 'Microsoft.PowerShell.Utility\Write-Host') Invoke-Expression "function Global:Write-HostOriginal { $([System.Management.Automation.ProxyCommand]::create($metaData)) }" } # https://msdn.microsoft.com/en-us/library/system.consolecolor(v=vs.110).aspx # Converted to closest ANSI SGR equivalent $AnsiColor = [pscustomobject][ordered]@{ # doit etre embarque (pour les scriptblock) ForeGround = [pscustomobject][ordered]@{ Black = 30 Red = 91 DarkRed = 31 Green = 92 DarkGreen = 32 Yellow = 93 DarkYellow = 33 Blue = 94 DarkBlue = 34 Magenta = 95 DarkMagenta = 35 Cyan = 96 DarkCyan = 36 White = 97 Gray = 37 DarkGray = 90 } BackGround = [pscustomobject][ordered]@{ Black = 40 White = 107 Red = 101 DarkRed = 41 Green = 102 DarkGreen = 42 Yellow = 103 DarkYellow = 43 Blue = 104 DarkBlue = 44 Magenta = 105 DarkMagenta = 45 Cyan = 106 DarkCyan = 46 Gray = 47 DarkGray = 100 } style = [pscustomobject][ordered]@{ RESET = 0 BOLD_ON = 1 ITALIC_ON = 3 UNDERLINE_ON = 4 BLINK_ON = 5 REVERSE_ON = 7 # BOLD_OFF = 22 # ITALIC_OFF = 23 # UDERLINE_OFF = 24 # BLINK_OFF = 25 # REVERSE_OFF = 27 } } function Colorize-Text { <# .SYNOPSIS Adds ANSI SGR codes to a string. .DESCRIPTION Adds ANSI SGR codes to a string. .PARAMETER text Text to be transformed. .PARAMETER ansiSgrCode ANSI SGR number to insert. See https://en.wikipedia.org/wiki/ANSI_escape_code for details Or use the [AnsiColor] enum. Also accepts an array of SGR numbers, and will apply all of them. .NOTES Designed to play nicely with https://wiki.jenkins-ci.org/display/JENKINS/AnsiColor+Plugin .EXAMPLE Colorize-Text 'toto' 7,93,101 #> param( $object, [int[]]$ansiCodes #https://en.wikipedia.org/wiki/ANSI_escape_code#graphics ) return "$([char]27)[$($ansiCodes -join(';'))m$object$([char]27)[0m" } $ansiCodes = @() if($style){ $ansiCodes += $AnsiColor.style.$style } if($foregroundColor){ $ansiCodes += $AnsiColor.ForeGround.$foregroundColor } if($backgroundColor) { $ansiCodes += $AnsiColor.BackGround.$backgroundColor } # Write-HostOriginal (Colorize-Text $object -ansiCodes $ansiCodes ) -nonewline # | Out-Host # (Colorize-Text $object -ansiCodes $ansiCodes ) | Out-Host # [Console]::Write( (Colorize-Text $object -ansiCodes $ansiCodes ) ) if($foregroundColor -and $backgroundColor){ # Write-HostOriginal (Colorize-Text $object -ansiCodes $ansiCodes ) -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor -nonewline # | Out-Host $global:ConsoleOutput += (Colorize-Text $object -ansiCodes $ansiCodes ) } elseif($foregroundColor){ # Write-HostOriginal (Colorize-Text $object -ansiCodes $ansiCodes ) -ForegroundColor $foregroundColor -nonewline # | Out-Host $global:ConsoleOutput += (Colorize-Text $object -ansiCodes $ansiCodes ) } elseif($backgroundColor){ # Write-HostOriginal (Colorize-Text $object -ansiCodes $ansiCodes ) -BackgroundColor $backgroundColor -nonewline # | Out-Host $global:ConsoleOutput += (Colorize-Text $object -ansiCodes $ansiCodes ) } else { # Write-HostOriginal $object -nonewline # | Out-Host $global:ConsoleOutput += $object } if (!$nonewline) { Write-HostOriginal $global:ConsoleOutput # -NoNewline $global:ConsoleOutput = '' # Write-HostOriginal '$!' -fore magenta } } } else { # $metaData = New-Object System.Management.Automation.CommandMetaData (Get-Command 'Microsoft.PowerShell.Utility\Write-Host') # Invoke-Expression "function Global:Write-HostOriginal { $([System.Management.Automation.ProxyCommand]::create($metaData)) }" } function Write-Object ([Parameter(ValueFromPipeline = $true)]$Object, $Depth = 1, [ConsoleColor]$foreGroundColor, [ConsoleColor]$backGroundColor = 'DarkGreen',[switch]$PassThru) { <# .SYNOPSIS Affiche le contenu d'un object .DESCRIPTION Converti en JSON et affiche sur plusieurs niveau  .PARAMETER Object Object a afficher .PARAMETER Depth Limite la profondeur a affichier .PARAMETER foreGroundColor Couleur du texte .PARAMETER backGroundColor couleur du fond .EXAMPLE affiche en rouge sur fond gris Write-Object $Obj -fore red -back gray .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> begin{ if ($ForegroundColor){ $color += @{ ForegroundColor = $ForegroundColor } } if ($BackgroundColor){ $color += @{ BackgroundColor = $BackgroundColor } } } process{ write-host "L.$($Myinvocation.ScriptlineNumber) $((Get-PSCallStack)[1].Command)`n",($Object | convertTo-Json -Depth $Depth) @color if ($PassThru) { $Object } } end{} } function Write-Center { <# .SYNOPSIS Ecrit un texte centre .DESCRIPTION Centre un texte par rapport a la largeur de la console  .PARAMETER text Texte du centre .PARAMETER Width Largeur prise en compte, par defaut .PARAMETER BackgroundColor Couleurs de fond .PARAMETER ForegroundColor Couleurs de texte .EXAMPLE while(1){cls;Write-Center '<!>';Start-Sleep -m 30;} .EXAMPLE while(1){cls;Write-Center '<!>' -ex 'X';Start-Sleep -m 30;} .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> param ( [String]$text = '================', [ValidateRange(10,1000)][int]$Width = $(if($host.ui.RawUI.WindowSize.Width -gt 10 -and !$JENKINS){$host.ui.RawUI.WindowSize.Width}else{200}), [ConsoleColor]$BackgroundColor = 'Magenta', [ConsoleColor]$ForegroundColor, [string]$extremity = '-' ) $left = [int](($Width - $text.length)/2) if ($ForegroundColor){ $color += @{ ForegroundColor = $ForegroundColor } } if ($BackgroundColor){ $color += @{ BackgroundColor = $BackgroundColor } } if($extremity) { $left = [int]($left - $extremity.Length) + $text.length $total = $Width-$extremity.Length*2 Write-Host "$($extremity+($text.PadLeft($left).PadRight($total))+$extremity)" @color } else { Write-Host ($text.PadLeft($left+$text.length)).PadRight($Width) @color } } function Write-Color { <# .SYNOPSIS Ecrit une serie de texte en couleur .DESCRIPTION chaque element de la liste utilisera la couleur suivante dans les listes ForeGroundColor et BackGroundColor  .PARAMETER Text liste des testes .PARAMETER ForeGroundColor liste des couleurs de texte .PARAMETER BackGroundColor liste des couleurs de fond .PARAMETER NoNewline Pas de nouvelle ligne a la fin .EXAMPLE Write-Color 1,2,3,4,5,6 -fore red,gray .EXAMPLE 730..749 | Write-Color -fore red,Gray -back black,black,cyan,cyan .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> [CmdletBinding()] param( [Parameter(ValueFromPipeline = $true)][String[]]$Texts, [ConsoleColor[]]$ForeGroundColor, [ConsoleColor[]]$BackGroundColor, [switch]$NoNewline ) begin { $i = 0 } process { foreach ($text in $Texts) { $Color = @{} if ($ForegroundColor){ $color += @{ ForegroundColor = $ForeGroundColor[$i%($ForeGroundColor.count)] } } if ($BackgroundColor){ $color += @{ BackgroundColor = $BackGroundColor[$i%($BackGroundColor.count)] } } try { Write-Host $text @color -NoNewLine # chaque texte a la suite, sans espace, ni retour a la ligne } catch {} $i++ } } end { try { if (!$NoNewline) { Write-Host } # '$!' -fore red } } catch {} } } $script:logStepPreference = $true function Write-LogStep { <# .SYNOPSIS Affiche une ligne de log a l'ecran .DESCRIPTION Affiche une etape a l'ecran, avec possibilité de le mettre dans un fichier ou le log event d'un serveur  .PARAMETER messages liste de [string] la 1er sera l'intitulé de la ligne .PARAMETER mode sera lié a la couleur .PARAMETER MaxWidth largeur totale en Nb de caractere .PARAMETER EachLength longueur des differents segment de texte - status : en Nb de caractere - prefixe : en Nb de caractere - title : en proportion du reste (MaxWidth-(status+prefixe)) - message : en proportion du reste (MaxWidth-(status+prefixe)) .PARAMETER prefixe texte cour avec 2 pattern possible (et autre conbinaison) %Line% %Caller% .PARAMETER LogTrace Peut etre : un [boulean] - $true active juste la sortie ecran - $false ou $null > pas de sortie ecran une [string] chemin de fichier de log ou un Fqdn / Computernane (implique [$true] = sortie ecran) - dans le 1er cas cela ajoutera une ligne a la fin du fichier - dans l'autre cas il y aura ajout d'event dans les Logs systeme du serveur .EXAMPLE Write-LogStep 'Print Log','Printed','cool' ok .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> param ([string[]]$messages, [ValidateSet('OK','Info','Warn','Error','Wait','Other')]$mode='Info', $MaxWidth=$(if($host.ui.RawUI.WindowSize.Width -gt 80 -and !$JENKINS){$host.ui.RawUI.WindowSize.Width}else{200}), $EachLength=@{status=10;prefixe=24;title=0.3;message=0.7}, $prefixe = 'L.%Line% %Caller%', $logTrace = $true # true retour ecran, fichier ou serveur implique $true ) if (!$PSBoundParameters.ContainsKey('logTrace')){ # si pas de nouvelle consigne alors on la reprend celle par defaut # write-host 363,$logTrace -fore Red if($script:logStepPreference -is [string] -and $script:logStepPreference -match 'false|true'){$script:logStepPreference=[bool]$script:logStepPreference} $logTrace = $script:logStepPreference } if ($logTrace){ # avec priorité a la nouvelle methode #if ($DebugPreference -like 'Silently*' -and $mode -notlike 'Error') { # return; #} # 'Continue' 'Stop' 'Inquire' switch ($mode) { 'OK'{ $status = ' OK ' $color = 'Green' $log_mode = 'Action' $log_type = 'SuccessAudit' } 'Info'{ $status = ' Info ' $color = 'Cyan' $log_mode = 'Querry' $log_type = 'Information' } 'Warn'{ $status = ' Warn ' $color = 'Yellow' $log_mode = 'Action' $log_type = 'Warning' } 'Error'{ $status = ' Error! ' $color = 'Red' $log_mode = 'Action' $log_type = 'Error' } 'Wait'{ $status = ' Wait ' $color = 'Magenta' $log_mode = 'Querry' $log_type = 'Information' } default{ $status = ' Other? ' $color = 'Gray' $log_mode = 'Querry' $log_type = 'Information' } } $Prefixe = ($prefixe -replace ('%Caller%',$((Get-PSCallStack)[1].Command)) -replace ('%Line%',$($Myinvocation.ScriptlineNumber))) $Prefixe = $(if ($Prefixe.length -gt $EachLength.prefixe-3) { " $($Prefixe.subString(0, $EachLength.prefixe-4)). " } elseif($Prefixe.length -gt 0) { " $($prefixe.padright($EachLength.prefixe-2))" } else {' '}) $EachLength.title = [int](($MaxWidth-($EachLength.status+$EachLength.prefixe)) * $EachLength.title) $EachLength.message = [int](($MaxWidth-($EachLength.status+$EachLength.prefixe)) * $EachLength.message) $title = $(if ($messages[0].length -gt $EachLength.title-3) { "$($messages[0].subString(0, $EachLength.title-4)). : " } elseif($messages[0].length -gt 0) { "$($messages[0].padright($EachLength.title-3,'.')) : " } else { $EachLength.message = $MaxWidth-($EachLength.status+$EachLength.prefixe) '' }) $messages = $messages[1..($messages.count)] if($Global:lastWritelogstep){ $time = (Get-date) - $Global:lastWritelogstep if ($time.TotalSeconds -gt 10) { $time = " $([Math]::Round($time.totalSeconds,1))s" } elseif ($time.TotalSeconds -gt 1) { $time = " $([Math]::Round($time.totalSeconds,2))s" } else { $time = " $([Math]::Round($time.MilliSeconds,0))ms" } $EachLength.message = $EachLength.message - $time.length } $Display = $(if ($EachLength.message -and ($messages -join(', ')).length -gt $EachLength.message) { "$(($messages -join(', ')).subString(0, $EachLength.message))" } else { $messages -join(', ') }) -replace("`n|`r",'') $Global:lastWritelogstep = (Get-date) # write-host 448,$logTrace -fore Red $script:logStepPreference = $logTrace if($logTrace -is [bool]){ Write-color '[',$status,']'.PadRight($EachLength.status-10), $prefixe, $title, $Display, $time -foregroundcolor white,$color,white,Gray,Cyan,$color,DarkGray } elseif ($logTrace -is [string]) { Write-color '[',$status,']'.PadRight($EachLength.status-10), $prefixe, $title, $Display, $time -foregroundcolor white,$color,white,Gray,Cyan,$color,DarkGray try { if (Test-TcpPort $logTrace 135 -Quick -ConfirmIfDown) { Add-LogEvent -ComputerName $logTrace -MessageContent "$(Get-date)`t[$status]`n$($title) $($messages -join(", "))`n" -mode $log_mode -target Others -Type $log_type } elseif (test-path $logTrace -PathType Leaf -IsValid) { # + ([Environment]::NewLine) [System.IO.File]::AppendAllText($logTrace, "$(Get-date)`t[$status]`t $prefixe $($title) $($messages -join(", "))`n" , [Text.Encoding]::UTF8) } else { # write-host "460"-fore Red $script:logStepPreference = $null } } catch { write-host "L.$($_.InvocationInfo.ScriptLineNumber)",$_ -fore Red # write-host "Add-LogEvent -ComputerName $logTrace -MessageContent `"$(Get-date)`t[$status]`n$($title) $($messages -join(", "))`n`" -mode $log_mode -target Others -Type $log_type" -fore Red } } elseif($logTrace -is [System.Windows.Forms.RichTextBox]) { Write-color '[',$status,']'.PadRight($EachLength.status-10), $prefixe, $title, $Display, $time -foregroundcolor white,$color,white,Gray,Cyan,$color,DarkGray try { $logTrace.SelectionColor = 'black' $logTrace.AppendText('[') $logTrace.SelectionColor = $color $logTrace.AppendText($status) $logTrace.SelectionColor = 'black' $logTrace.AppendText("]`t") $logTrace.SelectionColor = 'Gray' $logTrace.AppendText($prefix) $logTrace.SelectionColor = 'Blue' $logTrace.AppendText($title) $logTrace.SelectionColor = $color $logTrace.AppendText($($messages -join(", "))) $logTrace.SelectionColor = 'DarkGray' $logTrace.AppendText("$time`r`n") $logTrace.ScrollToCaret() } catch { write-host "L.$($_.InvocationInfo.ScriptLineNumber)",$_ -fore Red $script:logStepPreference = $true } } } else { # Write-Host 488,'.' -fore $color $script:logStepPreference = $null } } function Convert-toProgressBarre (<#[ValidateRange(0, 1)]#>$value, $Length=60, $block = [char]888, $empty= [char]903) { <# .SYNOPSIS Genere un barre de progression en TXT only .DESCRIPTION barre de progression en mode Text Utilisateion CLI  Utilisation Form.ListView  .PARAMETER value une valeur entre 0 et 1 qui correspond au pourcentage .PARAMETER Length longueur totale de la string de sortie .PARAMETER block caractere pour la charge .PARAMETER empty caractere pour les empty .EXAMPLE Convert-toProgressBarre .NOTES Alban LOPEZ 2018 alban.lopez@gmail.com http://git/PowerTech/ #> if ($value -gt 1) { $value = 1 } elseif ($value -lt 0) { $value = 0 } $load = "".PadLeft([Math]::Round($value*$Length),$block).padright($length,$empty) # iso largeur # $load = (20..255 | %{[char]$_}) -join('')#'-') return "[$load]" } function Write-ProgressBarreColor { <# .SYNOPSIS Affiche une bare de Progression en mode CLI .DESCRIPTION Affiche une barre de progression 3 couleurs dans la console, capable de remplace cette ligne pour afficher a nouveau  .PARAMETER Percents Longueur des segments [Vert], [Jaune] et [Rouge] separe par un "~" "[Vert]/[Jaune]/[Rouge]" les valeurs a 0 ou omise seront ignorée .PARAMETER Width Largeur de la bare affichee .PARAMETER replaceLine Actualise la bare ou trace une nouvelle ligne .PARAMETER block Numero du caractere UTF8, partie 'pleine' .PARAMETER empty Numero du caractere UTF8, partie 'vide' .EXAMPLE barre de 100 carctere de large "41~22~16" | Write-ProgressBarreColor -Width 100 .EXAMPLE random sur newline 1..9 | %{ "$(Get-Random -Minimum 40 -Maximum 50)~$(Get-Random -Minimum 20 -Maximum 30)~$(Get-Random -Minimum 5 -Maximum 10)";start-sleep -m 100 } | Write-ProgressBarreColor .EXAMPLE Random avec actualisation 1..9 | %{ "$(Get-Random -Minimum 40 -Maximum 50).2~$(Get-Random -Minimum 20 -Maximum 30).561~$((Get-Random -Maximum 1000)/100)";start-sleep -m 250 } | Write-ProgressBarreColor -Width 100 -replaceLine .NOTES Alban LOPEZ 2018 alban.lopez@gmail.com http://git/PowerTech/ #> param( [Parameter(ValueFromPipeline = $true)] [string[]]$Percents = '0~0~0', $Width = $host.ui.RawUI.WindowSize.Width-4, [string]$BarName = "Bar0", [switch]$replaceLine, [char]$block = $(if(!$JENKINS){9632}else{'#'}), [char]$empty = $(if(!$JENKINS){183}else{'-'}) # 8729 ) begin { if ($replaceLine) { #$replace = "`r" if (!$script:CursorLeft -and !$script:CursorTop){ try{ $script:CursorLeft = [Console]::CursorLeft $script:CursorTop = [Console]::CursorTop } catch {} } } else {$replace = ''} $Width = $Width - 2 try{ [Console]::CursorVisible = 0 } catch {} } process { foreach ($Percent in $Percents) { ([float]$green, [float]$yellow, [float]$red, $none) = $Percent.split('~') if ($green -lt 0) {$green = 0} elseif ($green -gt 100) {$green = 100} if ($yellow -lt 0) {$yellow = 0} elseif ($yellow -gt 100) {$yellow = 100} if ($red -lt 0) {$red = 0} elseif ($red -gt 100) {$red = 100} $greenLenght = [int]($green / 100 * $Width) $yellowLenght = [int]($yellow / 100 * $Width) $redLenght = [int]($red / 100 * $Width) $noneLenght = $Width - $greenLenght - $yellowLenght - $redLenght if ($noneLenght -lt 0) {$noneLenght = 0} elseif ($noneLenght -gt $Width) {$noneLenght = $Width} $total = [math]::round($green + $yellow + $red, 1) if ($replaceLine) { try{ [Console]::SetCursorPosition($script:CursorLeft, $script:CursorTop) } catch {} } Write-Color "$replace[", ` ''.PadLeft($greenLenght, $block) , ` ''.PadLeft($yellowLenght, $block) , ` ''.PadLeft($redLenght, $block) , ` ''.PadLeft($noneLenght, $empty) , ` '] ' ` -ForeGroundColor White, Green, Yellow, Red, gray, White ` -NoNewline $percent = "$('{0:00.0}' -f $total)" try{ [Console]::SetCursorPosition($Width - $percent.length - 2 , [Console]::CursorTop) } catch {} Write-Host $percent -ForegroundColor Cyan -NoNewline try{ [Console]::SetCursorPosition([Console]::CursorLeft + 1, [Console]::CursorTop) } catch {} Write-Host '%' -NoNewline try{ [Console]::SetCursorPosition($Width + 2, [Console]::CursorTop) } catch {} Write-Host '' #-NoNewline:$replaceLine #-BackGroundColor $dbc,Green,Yellow,Red,$dbc,$dbc ` } } end { try{ [Console]::CursorVisible = 1 } catch {} } } function Add-LogEvent { <# .SYNOPSIS Ajoute une entree dans le Observateur d'evenement .DESCRIPTION cree une ligne dans les logs du serveurs, dans [Journaux des application / ASP]  .PARAMETER ComputerName Nom DNS du Serveur cible .PARAMETER MessageContent Corp du Message de log .PARAMETER mode Mode d'interaction a logger .PARAMETER target Cible de l'interaction logger .PARAMETER Type Type d'interaction a logger .EXAMPLE ajoute un log au vdiv05 Add-LogEvent vdiv05 .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> param ( [ValidateNotNullOrEmpty()] [string]$ComputerName, [string]$MessageContent, [ValidateSet('Querry', 'Action', 'Update')] [string]$mode = 'Querry', [ValidateSet('Sessions', 'Process', 'Services', 'Registry', 'FileSystem', 'System', 'Software', 'Others')] [string]$target = 'Others', [ValidateSet('Error', 'Warning', 'Information', 'SuccessAudit', 'FailureAudit')] [string]$Type = 'Information' ) $ID = [pscustomobject][ordered]@{ Querry = 0 Action = 10 Update = 20 Sessions = 1 Process = 2 Services = 3 Registry = 4 FileSystem = 5 System = 6 Software = 7 Share = 8 Others = 9 } $ID = 30000 + $ID.$mode + $ID.$target $MessageContent = "[$(whoami)]`n$MessageContent" if ((Test-TcpPort $ComputerName).Time) { try { New-EventLog -ComputerName $ComputerName -LogName 'Coaxis-ASP' -Source "$Mode $Target" -EA 0 -WA 0 | out-null } catch { Write-host $_ fore red } try { Write-EventLog -Category 2 -ComputerName $ComputerName -LogName 'Coaxis-ASP' -Source "$Mode $Target" -EntryType $Type -EventID $ID -Message ($MessageContent -replace ('(<[^>]+>)', '')) } catch { Write-host $_ fore red } } } Function Test-TcpPort { <# .SYNOPSIS Test un port TCP distant .DESCRIPTION Tente l'ouverture d'un socket Tcp-Ip et retourne le le temps et le Status du test  .PARAMETER DestNode Noeuds a tester, unique ou sous forme d'une liste .PARAMETER port Numero du port Tcp-Ip a tester .PARAMETER timeout Duree maximum par noeud .PARAMETER ConfirmIfDown Retest une fois en cas d'echec, pour etre certain (car certain equipement ne reponde pas du 1er coup) .PARAMETER Quick retourne juste True (port ouvert) or False .EXAMPLE Test-TcpPort 8.8.8.8 53 -ConfirmIfDown .EXAMPLE tester un noeud avant une action if((Test-TcpPort $ipAddress -port 80 -ConfirmIfDown).time){ # Actions reseau sur ce noeud } .NOTES 👉 Alban LOPEZ 2018 👣 alban.lopez@gmail.com 💛 http://git/PowerTech/ #> Param( [Parameter(ValueFromPipeline = $true)]$DestNodes, $port = 135, $timeout = 100, [switch]$ConfirmIfDown, [switch]$Quick ) Begin { } Process { foreach ($destNode in $DestNodes) { $tcpclient = new-Object system.Net.Sockets.TcpClient # Create TCP Client $iar = $null $info = 'Open' try { $iar = $tcpclient.BeginConnect("$DestNode", $port, $null, $null) # Tell TCP Client to connect to machine on Port $timeMs = (Measure-Command { $wait = $iar.AsyncWaitHandle.WaitOne($timeout, $false) # Set the wait time }).TotalMilliseconds } catch { # Write-verbose $_ } # Check to see if the connection is done if (!$wait) { # Close the connection and report timeout $timeMs = $null $info = 'TimeOut!' $tcpclient.Close() if ($ConfirmIfDown) { $retry = Test-TcpPort -dest $destNode -port $port -timeOut $timeOut $timeMs = $retry.time $info = $retry.Infos } } else { try { $tcpclient.EndConnect($iar) | out-Null $tcpclient.Close() } catch { $timeMs = $null $info = 'Unknow Host!' } } if ($Quick){ [bool]$timeMs } else { [pscustomobject]@{ DestNode = "$DestNode" TcpPort = $port Time = $timeMs Infos = $info #'ICMP' = (test-connection $DestNode -quiet -count 1) } } $tcpclient.Close() } } End { } } # Write-logstep 'Chargement du module ',$PSCommandPath ok Write-logstep -prefix "L.$($_.InvocationInfo.ScriptLineNumber) $((Get-PSCallStack)[1].Command)" 'Chargement du module ',$PSCommandPath ok |