PsWrite.psm1
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 |