Commun/VegaShellCommun.ps1
function TryCatchError { <# .SYNOPSIS This function throws an error in a try-catch block with several options: <br>1. Continue despite the error with [switch]continue <br>2. Modify the default $PSItem variable <br>3. Send a Windows popup .DESCRIPTION $continue --> continue or not despite the error $LastError --> change the default value which is $PSItem $Popup --> send a popup on the Windows session .EXAMPLE try { blabla } catch { TryCatchError OR TryCatchError -Continue -Popup } #> [CmdletBinding()] param ( [Parameter(Mandatory=$false)] [switch]$Continue, [Parameter(Mandatory=$false)] [switch]$Popup, [Parameter(Mandatory=$false)] $LastError = $PSItem ) process { Write-Information "Script in error line $($LastError.InvocationInfo.ScriptLineNumber)" Write-Information "Error message: $($LastError.Exception.Message)" } end { if (!$Continue) { throw $LastError } if ($Popup) { PopUpWindows -level error -Title "Error Line $($LastError.InvocationInfo.ScriptLineNumber)" -Message "$($LastError.Exception.Message)" } } } function RebootService { <# .SYNOPSIS Cette fonction sert a relancer un service et forcer par kill du pid si blocage .DESCRIPTION Service --> liste au format array .EXAMPLE $services = (get-service).DisplayName SelectItemListed $services #> param( [ValidateScript({ Get-Service $_ })] [Parameter(Mandatory = $true)] $Service ) begin { $stopped = $false $ServiceStatus = (Get-Service $Service) } process { if ($ServiceStatus.Status -eq "Stopped") { $stopped = $true return } try { $ServiceStatus.Stop() $ServiceStatus.WaitForStatus("Stopped", '00:00:15') while ($ServiceStatus.Status -ne "Stopped") { Write-Information "Le service $Service ne s arrete pas, le processus va etre kill" #trouve le Pid correspondant au processus du service et le kill [array]$ID = tasklist /FI "services eq $service" $ID = ([regex]::Matches($ID, "\d{2,5}") | Select-Object -first 1 ).value taskkill /PID $ID /f $ServiceStatus = (Get-Service $Service) start-sleep 2 } ($ServiceStatus).start() | ForEach-Object ($ServiceStatus).WaitForStatus("running") } catch { TryCatchError } } end { if ($stopped -eq $true) { Write-Output "Service déja stoppé" } elseif ($stopped -eq $false) { Write-Output "service ok" } } } Function SelectItemListed { <# .SYNOPSIS Cette fonction sert a lister des variables et d'extraire la ligne choisis manuellement (peu etre utilisé frompipeline) .DESCRIPTION Itemlist --> liste au format array .EXAMPLE $services = (get-service).DisplayName SelectItemListed $services ou (get-service).DisplayName | SelectItemListed #> param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory = $true, ValueFromPipeline = $true)] [array]$Itemlist ) begin { Add-Type -AssemblyName System.Windows.Forms Add-Type -AssemblyName System.Drawing $form = New-Object System.Windows.Forms.Form $form.Text = 'Select a Computer' $form.Size = New-Object System.Drawing.Size(400, 350) $form.StartPosition = 'CenterScreen' $okButton = New-Object System.Windows.Forms.Button $okButton.Location = New-Object System.Drawing.Point(125, 275) $okButton.Size = New-Object System.Drawing.Size(75, 23) $okButton.Text = 'OK' $okButton.DialogResult = [System.Windows.Forms.DialogResult]::OK $form.AcceptButton = $okButton $form.Controls.Add($okButton) $cancelButton = New-Object System.Windows.Forms.Button $cancelButton.Location = New-Object System.Drawing.Point(200, 275) $cancelButton.Size = New-Object System.Drawing.Size(75, 23) $cancelButton.Text = 'Cancel' $cancelButton.DialogResult = [System.Windows.Forms.DialogResult]::Cancel $form.CancelButton = $cancelButton $form.Controls.Add($cancelButton) $label = New-Object System.Windows.Forms.Label $label.Location = New-Object System.Drawing.Point(10, 20) $label.Size = New-Object System.Drawing.Size(280, 20) $label.Text = 'Please select a computer:' $form.Controls.Add($label) $listBox = New-Object System.Windows.Forms.ListBox $listBox.Location = New-Object System.Drawing.Point(10, 40) $listBox.Size = New-Object System.Drawing.Size(365, 20) $listBox.Height = 200 } process { Foreach ($Resultstype in $Itemlist) { #Remplie le tableau de l'interface avec les resultats [void]$listBox.Items.Add("$($Resultstype)") } $form.Controls.Add($listBox) } end { $form.Topmost = $true $selectResult = $form.ShowDialog() if ($selectResult -eq [System.Windows.Forms.DialogResult]::OK) { $valeur = $listBox.SelectedItem Write-Information "Voici la valeur selectionnée " return $valeur } elseif ($selectResult -eq [System.Windows.Forms.DialogResult]::Cancel) { Write-Output "Choix annulé" break } } } function PopUpWindows { <# .SYNOPSIS Cette fonction sert a faire apparaitre un popup windows .DESCRIPTION $level --> niveau de criticité $Titre --> titre du popup $message --> message du popup retourne 1 si succes retourne 0 si echec .EXAMPLE PopUpWindows -level warning -Titre titretest -Message message1 #> param( [ValidateSet("info", "warning", "error")] [string]$level = "info", [ValidateNotNullOrEmpty()] [Parameter(Mandatory = $true)] [string]$Titre, [ValidateNotNullOrEmpty()] [Parameter(Mandatory = $true)] [string]$Message ) begin { $PSDefaultParameterValues['*:Encoding'] = 'utf8' [void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") $notify = New-Object system.windows.forms.notifyicon $path = Get-Process -id $pid | Select-Object -ExpandProperty Path $icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path) $notify.icon = $icon $notify.visible = $true } process { try { $notify.showballoontip(10, $Titre, $Message, [system.windows.forms.tooltipicon]::$level) Write-Output "Popup envoyé" return 1 } catch { TryCatchError -continue return 0 } } } function SendMsgToTeams { <# .SYNOPSIS Cette fonction sert a envoyer un msg teams via webhook .DESCRIPTION $WebhookURL --> url du webhook $Titre --> titre du msg $Message --> corp du msg $Couleur --> couleur de la barre $Card --> pour envoyer une carte au lieu d'un msg retourne 1 si succes retourne 0 si echec .EXAMPLE SendMsgToTeams -WebhookURL $url -Title Merci -Message Cordialment -couleur vert SendMsgToTeams -WebhookURL $url -Card $mscard #> param( [ValidateNotNullOrEmpty()] [Parameter(Mandatory = $true)] [string]$WebhookURL, [ValidateNotNullOrEmpty()] [Parameter(Mandatory = $false)] [string]$Titre, [ValidateNotNullOrEmpty()] [Parameter(Mandatory = $false)] [string]$Message, [Parameter(Mandatory = $false)] [ValidateSet("vert", "jaune", "rouge")] [string]$Couleur, [Parameter(Mandatory = $false)] [ValidateNotNullOrEmpty()] [string]$Card ) begin { switch ($couleur) { #si choix 1 vert { $color = '008000' } #si choix 2 jaune { $color = 'FFFF00' } #si choix3 rouge { $color = 'FF0000' } } # Hashtable for the body of Teams message if ($card) { $Body = $Card } else { $Body = @{ Title = $Titre text = $message themeColor = $color } | ConvertTo-Json } # Build the request $Param = @{ Headers = @{'accept' = 'application/json' } Body = $Body Method = 'Post' URI = $WebhookURL ContentType = "application/vnd.api+json; charset=utf-8" } } process { # Send the request to Microsoft Teams Try { Invoke-RestMethod @Param Write-Output "Message envoyé" } Catch { Write-Error "Erreur ! Impossible d'envoyer le msg teams" TryCatchError -continue return 0 } } } Function Test-ServerConnection { <# .SYNOPSIS This function tests the connectivity of a server by sending a ping request. Returns 0 if successful, 1 otherwise. .DESCRIPTION $Server --> name or adress .EXAMPLE Test-ServerConnection -Server 'S830701SQL011' #> [CmdletBinding()] [OutputType("System.Int32")] param( [Parameter(Mandatory = $true)] [string]$Server ) try { $ping = New-Object System.Net.NetworkInformation.Ping $result = $ping.Send($Server) if ($result.Status -eq 'Success') { Write-Verbose "Connection to $Server successful." return 0 } else { Write-Verbose "Connection to $Server failed." return 1 } } catch { Write-Error "Error occurred while testing connection to $Server`: $_" return 1 } } |