Sans partage, la connaissance n'est rien !
Fil de navigation
- Détails
- Écrit par Pierre JACQUOT
- Catégorie : Scripts
- Affichages : 114
Ce script créé par mes soins permet d'exporter la liste des certificats installées avec leurs dates d'expiration dans un rapport HTML (trié par date). Les données ainsi que le rapport seront ensuite envoyés automatiquement par mail.
Fonctionnalités :
- Exporter la liste des certificats installées avec leurs dates d'expiration (Colonnes récupérées : FriendlyName, Start date, End date, Expires in, Thumbprint)
- Exporter les données dans un fichier .csv (trié par date)
- Exporter les données dans un rapport HTML (trié par date)
- Envoyer les données ainsi que le rapport HTML par mail
Utilisation :
- Compléter les variables suivantes dans le script :
- $MailFrom = "UserName[at]mail.fr" (Adresse mail de l'expéditeur)
- $MailTo = "UserName[at]mail.fr" (Adresse mail du destinataire)
- $MailSMTPServer = "SMTPServerName" (Serveur SMTP)
- $MailSMTPPort = "PortNumber" (Numéro du port SMTP)
Screenshot :
Code du script :
<#
.SYNOPSIS
Export certificates list with their expiration dates
.DESCRIPTION
Export certificates list with their expiration dates and sent the HTML report by email
.NOTES
File name : Get-Certificate.ps1
Author : Pierre JACQUOT
Date : 24/05/2020
Version : 1.0
.LINK
Website : https://www.pierrejacquot.yo.fr
Reference : https://www.pierrejacquot.yo.fr/index.php/scripts/45-script-get-certificate
#>
Clear-Host
$StartTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[string]$Hostname = [Environment]::MachineName
[string]$Login = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
[string]$Workfolder = Split-Path $MyInvocation.MyCommand.Path
[string]$Date = Get-Date -UFormat "%Y-%m-%d"
[string]$ExportFile = $Workfolder + "\$Date-Certificates-Report.html"
[array]$Certificates = Get-ChildItem -Path Cert:\LocalMachine\Root\ | Sort-Object NotAfter | Select-Object FriendlyName, @{Name="Start date";Expression={$_.NotBefore}}, @{Name="End date";Expression={$_.NotAfter}}, @{Name="Expires in";Expression={($_.NotAfter – (Get-Date))}}, Thumbprint
[int]$CertificatesNumbers = $Certificates.Count
[string]$Activity = "Trying to launch the export of [$CertificatesNumbers] certificate(s)"
[int]$Step = 1
Write-Host "Get-Certificate :" -ForegroundColor Black -BackgroundColor Yellow
Write-Host "Launching the export of [$CertificatesNumbers] certificate(s)." -ForegroundColor Cyan
Write-Host "`r"
If ($CertificatesNumbers -ge 1) {
[string]$MailFrom = "UserName[at]mail.fr"
[string]$MailTo = "UserName[at]mail.fr"
[string]$MailSubject = "[$Date] - Certificate(s) report on : $Hostname"
[string]$MailSMTPServer = "SMTPServerName"
[int]$MailSMTPPort = "PortNumber"
[string]$Style="<title>$MailSubject</title>
<style>
h1 { font-family: Arial; color: #e68a00; font-size: 28px; }
h2 { font-family: Arial; color: #000000; font-size: 16px; }
table { border: 0px; font-family: Arial; }
td { padding: 4px; margin: 0px; font-size: 12px; }
th { background: linear-gradient(#49708f, #293f50); color: #ffffff; font-size: 11px; padding: 10px 15px; }
tr:nth-child(even) { background-color: #f0f0f2; }
tr:hover { background-color: #ddd; }
.ExpiratedStatus { background-color: #000000; font-weight: bold; color: #ffffff; }
.CriticalStatus { background-color: #ff0000; font-weight: bold; color: #ffffff; }
.WarningStatus { background-color: #ffa500; font-weight: bold; color: #ffffff; }
.SuccessStatus { background-color: #008000; font-weight: bold; color: #ffffff; }
#PostContent { font-family: Arial; font-size: 11px; font-style: italic; }
span.PostContentBlue { color: #000099; }
</style>"
[string]$PreContent = "<h1>Certificate(s) overview : $Date</h1><h2>Number of certificate(s) : <span class='PostContentBlue'>$CertificatesNumbers</span> on <span class='PostContentBlue'>$Hostname</span></h2>"
[string]$CertificatesHTML = Get-ChildItem -Path Cert:\LocalMachine\Root\ | Sort-Object NotAfter | Select-Object FriendlyName, @{Name="Start date";Expression={$_.NotBefore}}, @{Name="End date";Expression={$_.NotAfter}}, @{Name="Expires in";Expression={($_.NotAfter – (Get-Date)).Days}}, Thumbprint | ConvertTo-Html -As Table -Fragment -PreContent $PreContent
ForEach ($Certificate in $Certificates) {
[string]$CertifName = $Certificate.FriendlyName
$CertifStart = $Certificate."Start date"
$CertifEnd = $Certificate."End date"
$Expiresin = $Certificate."Expires in"
$ExpiresinDays = $Expiresin.Days
$ExpiresinHours = $Expiresin.Hours
$ExpiresinMinutes = $Expiresin.Minutes
$ExpiresinSeconds = $Expiresin.Seconds
[string]$CertifThumbprint = $Certificate.Thumbprint
[string]$Status = "Processing [$Step] of [$CertificatesNumbers] - $(([math]::Round((($Step)/$CertificatesNumbers*100),0)))% completed"
[string]$CurrentOperation = "Exporting certificate : Name $CertifName - Start date : $(Get-Date $CertifStart -Format "dd/MM/yyyy HH:mm:ss") - End date : $(Get-Date $CertifEnd -Format "dd/MM/yyyy HH:mm:ss")"
Write-Progress -Activity $Activity -Status $Status -CurrentOperation $CurrentOperation -PercentComplete ($Step/$CertificatesNumbers*100)
$Step++
If ($CertifEnd -le (Get-Date)) {
$CertificatesHTML = $CertificatesHTML -replace "<td>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td>$ExpiresinDays</td>","<td class='CriticalStatus'>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td class='ExpiratedStatus'>This certificate has expired</td>"
}
Else {
If ($ExpiresinDays -le 10) {
$CertificatesHTML = $CertificatesHTML -replace "<td>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td>$ExpiresinDays</td>","<td class='SuccessStatus'>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td class='CriticalStatus'>$ExpiresinDays days $($ExpiresinHours):$($ExpiresinMinutes):$($ExpiresinSeconds)</td>"
}
ElseIf ($ExpiresinDays -ge 11 -and $ExpiresinDays -le 30) {
$CertificatesHTML = $CertificatesHTML -replace "<td>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td>$ExpiresinDays</td>","<td class='SuccessStatus'>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td class='WarningStatus'>$ExpiresinDays days $($ExpiresinHours):$($ExpiresinMinutes):$($ExpiresinSeconds)</td>"
}
Else {
$CertificatesHTML = $CertificatesHTML -replace "<td>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td>$ExpiresinDays</td>","<td class='SuccessStatus'>$(Get-Date $CertifEnd -Format 'dd/MM/yyyy HH:mm:ss')</td><td class='SuccessStatus'>$ExpiresinDays days $($ExpiresinHours):$($ExpiresinMinutes):$($ExpiresinSeconds)</td>"
}
}
}
Do {
$MailPass = Read-Host "Set the password of [$MailTo] mailbox " -AsSecureString
$MailPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($MailPass))
If ($MailPassword -eq "") {
Write-Host "Password is mandatory !" -ForegroundColor Red
Write-Host "`r"
}
} Until ($MailPassword -ne "")
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $MailTo, $MailPass
$EndTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[decimal]$Duration = [math]::Round((New-TimeSpan -Start $StartTime -End $EndTime).TotalSeconds,2)
[string]$PostContent = "<p id='PostContent'>Script launched from : <span class='PostContentBlue'>$Hostname</span><br/>By : <span class='PostContentBlue'>$Login</span><br/>Path : <span class='PostContentBlue'>$Workfolder</span><br/>Export file : <span class='PostContentBlue'>$(Split-Path $ExportFile -Leaf)</span><br/>Start time : <span class='PostContentBlue'>$StartTime</span><br/>End time : <span class='PostContentBlue'>$EndTime</span><br/>Duration : <span class='PostContentBlue'>$Duration</span> seconds</p>"
[string]$Report = ConvertTo-Html -Body "$CertificatesHTML" -Head $Style -PostContent $PostContent
$Report | Out-File -FilePath $ExportFile -Encoding utf8
Write-Host "Certificates report has been created : $ExportFile" -ForegroundColor Green
Try {
Send-MailMessage -From $MailFrom -To $MailTo -Subject $MailSubject -Body $Report -Priority High -Attachments $ExportFile -SmtpServer $MailSMTPServer -Port $MailSMTPPort -UseSsl -Credential $Credential -BodyAsHtml -Encoding UTF8
Write-Host "Certificates report with attached file : $(Split-Path $ExportFile -Leaf) has been sent by e-mail" -ForegroundColor Green
}
Catch {
[string]$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage -ForegroundColor Red
}
}
Write-Host "`r"
Write-Host "Script launched from : " -NoNewline; Write-Host $Hostname -ForegroundColor Red
Write-Host "By : " -NoNewline; Write-Host $Login -ForegroundColor Red
Write-Host "Path : " -NoNewline; Write-Host $Workfolder -ForegroundColor Red
Write-Host "Export file : " -NoNewline; Write-Host (Split-Path $ExportFile -Leaf) -ForegroundColor Red
Write-Host "Start time : " -NoNewline; Write-Host $StartTime -ForegroundColor Red
Write-Host "End time : " -NoNewline; Write-Host $EndTime -ForegroundColor Red
Write-Host "Duration : " -NoNewline; Write-Host $Duration -ForegroundColor Red -nonewline; Write-Host " seconds"
Write-Host "`r"
Cliquer ici pour visualiser un exemple du rapport Certificates-Report.html
créé automatiquement depuis mon poste.
Cliquer ici pour télécharger le script.
- Détails
- Écrit par Pierre JACQUOT
- Catégorie : Scripts
- Affichages : 161
Voici la procédure à suivre afin de créer son propre profile et charger la configuration que l’on souhaite à l’ouverture de PowerShell & ISE.
Procédure :
Identifiez le chemin de votre profile :
$PROFILE
Sous Windows 7, le résultat devrait être le suivant :
C:\Users\Pierre\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Vérifier la présence du profile :
Test-Path $PROFILE
Si la réponse est False, il faut au préalable créer le fichier en tapant la commande suivante :
New-Item -Path $PROFILE -Type File -Force
Si la réponse est True, vous pouvez directement éditer et ajouter toutes les commandes que vous souhaitez exécuter à l’ouverture de PowerShell.
Voici la commande à taper pour recharger votre profile automatiquement :
./$PROFILE
Note :
Le profil que l'on vient de créer s'applique uniquement à la console PowerShell, un fichier de profil nommé profile.ps1
s'applique à la fois à PowerShell ISE ainsi qu'à la console PowerShell, tandis qu'un fichier de profil nommé Microsoft.PowerShellISE_profile.ps1
s'applique seulement à PowerShell ISE.
Screenshots :
Code du script :
<#
.SYNOPSIS
Customize your PowerShell Profile.
.DESCRIPTION
Customizing your PowerShell Profile in order to automatically load scripts when you start the PowerShell console.
.NOTES
File name : Microsoft.PowerShell_profile.ps1
Author : Pierre JACQUOT
Date : 28/10/2018
Version : 1.0
.LINK
Website : https://www.pierrejacquot.yo.fr
Reference : https://www.pierrejacquot.yo.fr/index.php/scripts/44-configurer-son-profile-sous-windows-powershell-ise
#>
Set-Location -Path "D:\"
New-Item alias:np -Value "C:\Windows\System32\notepad.exe" | Out-Null
New-Item alias:np++ -Value "C:\Program Files\Notepad++\notepad++.exe" | Out-Null
Clear-Host
Function Test-Administrator {
$Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = New-Object Security.Principal.WindowsPrincipal $Identity
$Principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
Function Prompt {
[string]$Hostname = [Environment]::MachineName
[string]$Username = [Environment]::UserName
$Host.UI.RawUI.WindowTitle = "Windows PowerShell > Hostname : $Hostname > Username : $Username"
Write-Host "I " -NoNewline
Write-Host "$([char]9829) " -ForegroundColor Red -NoNewline
Write-Host "PS " -NoNewline
Write-Host "> " -ForegroundColor Yellow -NoNewline
Write-Host (Get-Date -UFormat "[%d-%m-%Y %H:%M:%S] ") -ForegroundColor Cyan -NoNewline
Write-Host "> " -ForegroundColor Yellow -NoNewline
Write-Host (Split-Path $PWD -Leaf) -ForegroundColor Green -NoNewline
If (Test-Administrator -eq $True) {
$Host.UI.RawUI.WindowTitle = "[Administrateur] - Windows PowerShell > Hostname : $Hostname > Username : $Username"
Write-Host " >" -ForegroundColor Yellow -NoNewline
Write-Host " [ADMIN]" -ForegroundColor Red -NoNewline
}
Write-Host " >_" -ForegroundColor Yellow -NoNewline
return " "
}
Cliquer ici pour télécharger le script.
- Détails
- Écrit par Pierre JACQUOT
- Catégorie : Scripts
- Affichages : 94
Ce script créé par mes soins permet de supprimer tous les fichiers de log d'un dossier qui n'ont pas été modifiés depuis 30 jours.
Fonctionnalités :
- Supprime des utilisateurs (informations stockées dans un fichier csv) en masse d'un ou de plusieurs groupes AD
- Création d'un fichier de logs horodatés (Purge-Folder)
- Exporter les données dans un fichier .csv
- Exporter les données dans un rapport HTML
Utilisation :
- Compléter les variables suivantes dans le script :
- $SourceFolder = "D:\Scripts\Purge-Folder\Logs" (Chemin d'accès aux fichiers de logs à purger)
- $ConditionFiles = $AllFiles | Where-Object { ($_.LastWriteTime -lt (Get-Date).AddDays(-30)) -and ($_.Name -like "Test*") -and ($_.Extension -eq ".txt") } (Définir le nombre de jours, le nom et l'extension des fichiers à purger)
Screenshot :
Code du script :
<#
.SYNOPSIS
Delete old log files
.DESCRIPTION
Delete all log files in a folder that haven't been modified in the last 30 days and export results
.NOTES
File name : Purge-Folder.ps1
Author : Pierre JACQUOT
Date : 07/02/2018
Version : 1.0
.LINK
Website : https://www.pierrejacquot.yo.fr
Reference : https://www.pierrejacquot.yo.fr/index.php/scripts/43-script-purge-folder
#>
Clear-Host
Function Write-Log([string]$Output, [string]$Message) {
Write-Verbose $Message
((Get-Date -UFormat "[%d/%m/%Y %H:%M:%S] ") + $Message) | Out-File -FilePath $Output -Append -Force
}
$StartTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[string]$Hostname = [Environment]::MachineName
[string]$Login = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
[string]$Workfolder = Split-Path $MyInvocation.MyCommand.Path
[string]$Date = Get-Date -UFormat "%Y-%m-%d"
[string]$CSVFile = $Workfolder + "\$Date-FilesRemoval-Export.csv"
[string]$ReportFile = $Workfolder + "\$Date-FilesRemoval-Report.html"
[string]$LogFile = $Workfolder + "\$Date-Purge-Folder.log"
[string]$SourceFolder = "D:\Scripts\Purge-Folder\Logs"
[array]$AllFiles = Get-ChildItem -Path $SourceFolder -Recurse
[array]$ConditionFiles = $AllFiles | Where-Object { ($_.LastWriteTime -lt (Get-Date).AddDays(-30)) -and ($_.Name -like "Test*") -and ($_.Extension -eq ".txt") }
$ConditionFiles | Add-Member -Type NoteProperty -Name "Status" -Value "N/A"
[int]$FilesNumber = $AllFiles.Count
[int]$ConditionFilesNumber = $ConditionFiles.Count
[string]$Activity = "Trying to launch the deletion of [$ConditionFilesNumber] log file(s)"
[int]$Step = 1
[string]$Title = "[$Date] - File(s) removal report on : $Hostname"
Write-Host "Purge-Folder :" -ForegroundColor Black -BackgroundColor Yellow
Write-Host "Launching the deletion of [$ConditionFilesNumber] log file(s)." -ForegroundColor Cyan
Write-Host "`r"
If ($FilesNumber -eq 0) {
Write-Warning "Source folder $SourceFolder is empty."
Write-Log -Output $LogFile -Message "Source folder $SourceFolder is empty."
}
ElseIf ($ConditionFilesNumber -eq 0) {
Write-Warning "Source folder $SourceFolder does not contain Test*.txt files older than 30 days."
Write-Log -Output $LogFile -Message "Source folder $SourceFolder does not contain Test*.txt files older than 30 days."
}
Else {
ForEach ($File in $ConditionFiles) {
[string]$FileName = $File.Name
$FileLastWriteTime = $File.LastWriteTime
[string]$Status = "Processing [$Step] of [$ConditionFilesNumber] - $(([math]::Round((($Step)/$ConditionFilesNumber*100),0)))% completed"
[string]$CurrentOperation = "Removing log file : $FileName - LastWriteTime : $FileLastWriteTime"
Write-Progress -Activity $Activity -Status $Status -CurrentOperation $CurrentOperation -PercentComplete ($Step/$ConditionFilesNumber*100)
$Step++
Start-Sleep -Seconds 1
Try {
$File.Status = "OK"
Remove-Item $File.FullName
Write-Host "$FileName has been removed - LastWriteTime : $FileLastWriteTime." -ForegroundColor Green
Write-Log -Output $LogFile -Message "$FileName has been removed - LastWriteTime : $FileLastWriteTime."
}
Catch {
$File.Status = "KO"
[string]$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage -ForegroundColor Red
Write-Log -Output $LogFile -Message $ErrorMessage
}
}
}
[array]$FileList = $ConditionFiles | Select-Object FullName, @{Name="Length (Ko)";Expression={"{0:N2}" -f ($_.Length/1024)}}, Extension, CreationTime, LastWriteTime, Status
$FileList | Export-Csv -Path $CSVFile -NoTypeInformation -Delimiter ";" -Encoding UTF8
$EndTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[decimal]$Duration = [math]::Round((New-TimeSpan -Start $StartTime -End $EndTime).TotalSeconds,2)
[string]$PreContent = "<h1>$Title</h1>
<h2>Number of file(s) : <span class='PostContentBlue'>$ConditionFilesNumber</span></h2>"
[string]$PostContent = "<p id='PostContent'>Script launched from : <span class='PostContentBlue'>$Hostname</span><br/>
By : <span class='PostContentBlue'>$Login</span><br/>
Path : <span class='PostContentBlue'>$Workfolder</span><br/>
CSV file : <span class='PostContentBlue'>$(Split-Path $CSVFile -Leaf)</span><br/>
Report file : <span class='PostContentBlue'>$(Split-Path $ReportFile -Leaf)</span><br/>
Log file : <span class='PostContentBlue'>$(Split-Path $LogFile -Leaf)</span><br/>
Start time : <span class='PostContentBlue'>$StartTime</span><br/>
End time : <span class='PostContentBlue'>$EndTime</span><br/>
Duration : <span class='PostContentBlue'>$Duration</span> second(s)</p>"
[string]$Report = $FileList | ConvertTo-Html -As Table -CssUri ".\Style.css" -Title $Title -PreContent $PreContent -PostContent $PostContent
$Report = $Report -replace '<td>OK</td>','<td class="SuccessStatus">OK</td>'
$Report = $Report -replace '<td>KO</td>','<td class="CriticalStatus">KO</td>'
$Report | Out-File -FilePath $ReportFile -Encoding utf8
Write-Host "`r"
Write-Host "Script launched from : " -NoNewline; Write-Host $Hostname -ForegroundColor Red
Write-Host "By : " -NoNewline; Write-Host $Login -ForegroundColor Red
Write-Host "Path : " -NoNewline; Write-Host $Workfolder -ForegroundColor Red
Write-Host "CSV file : " -NoNewline; Write-Host (Split-Path $CSVFile -Leaf) -ForegroundColor Red
Write-Host "Report file : " -NoNewline; Write-Host (Split-Path $ReportFile -Leaf) -ForegroundColor Red
Write-Host "Log file : " -NoNewline; Write-Host (Split-Path $LogFile -Leaf) -ForegroundColor Red
Write-Host "Start time : " -NoNewline; Write-Host $StartTime -ForegroundColor Red
Write-Host "End time : " -NoNewline; Write-Host $EndTime -ForegroundColor Red
Write-Host "Duration : " -NoNewline; Write-Host $Duration -ForegroundColor Red -nonewline; Write-Host " second(s)"
Write-Host "`r"
Exemple du fichier Purge-Folder.log
créé automatiquement avec les fichiers de log supprimés dans le dossier :
[10/05/2020 09:21:42] Test1.txt has been removed - LastWriteTime : 11/01/2018 10:50:58. [10/05/2020 09:21:43] Test2.txt has been removed - LastWriteTime : 11/01/2018 10:50:58. [10/05/2020 09:21:44] Test3.txt has been removed - LastWriteTime : 11/01/2018 10:50:58. [10/05/2020 09:21:45] Test4.txt has been removed - LastWriteTime : 11/01/2018 10:50:58.
Cliquer ici pour visualiser un exemple du rapport FilesRemoval-Report.html
créé automatiquement depuis mon poste.
Cliquer ici pour télécharger le fichier de style css.
Cliquer ici pour télécharger le script.
- Détails
- Écrit par Pierre JACQUOT
- Catégorie : Scripts
- Affichages : 135
Ce script créé par mes soins permet d'automatiser la création de machines virtuelles sur le vCenter à l'aide d'un fichier XML qui contient l’ensemble de la configuration des VMs à déployer.
Fonctionnalités :
- Créer des VMs (informations stockées dans un fichier XML) en masse sur le vCenter
- Création d'un fichier de logs horodatés (Create-VM)
Prérequis :
- Afin de pouvoir exécuter le script, il faut avoir les droits suivants :
- Admins du domaine (Pour pouvoir intégrer les VMs au domaine et pour la création des groupes AD : ADM et TSE)
- Admin de la plateforme VMware (Pour pouvoir créer des VMs et les modifier)
- Il faut également installer les outils suivants :
- Module Active Directory pour Windows PowerShell (Présent dans les [RSAT] : Outils d’administration de serveur distant pour Windows 7 et Windows 10)
- VMware PowerCLI
Utilisation :
- Compléter les variables suivantes dans le script :
- $TargetOU = "OU=AdministrationGroups,DC=test,DC=local" (Chemin de l'OU pour la création des groupes AD)
- $Connection = Connect-VIServer -Server vCenterServerName (Définir le nom de votre vCenter)
- $OSCustSpec = New-OSCustomizationSpec -Name $VMName -NamingScheme Fixed -NamingPrefix $VMName -OSType Windows -FullName Name -OrgName "OrgName" -ChangeSid -Domain "DomainName" -DomainUsername $Login -DomainPassword $Password -AdminPassword $AdminPassword -TimeZone 105 (Définir le nom complet, le nom de l'organisation et votre domaine AD)
Exemple du fichier VM-Configuration.xml
avec les informations de configuration des VMs :
<CreateVM>
<VM>
<VMName>VMName</VMName>
<Template>TemplateName</Template>
<Datacenter>DCName</Datacenter>
<Cluster>ClusterName</Cluster>
<ESX>ESXName</ESX>
<Datastore>DatastoreName</Datastore>
<Drive>40</Drive>
<Drive2>20</Drive2>
<Drive3>4</Drive3>
<CPU>2</CPU>
<MemoryGB>4</MemoryGB>
<VLAN>VLANName</VLAN>
<IP>192.XXX.XXX.XXX</IP>
<Mask>255.255.255.0</Mask>
<Gateway>192.XXX.XXX.XXX</Gateway>
<DNS>8.8.8.8 8.8.4.4</DNS>
<Description>Server Description</Description>
</VM>
</CreateVM>
Screenshot :
Code du script :
<#
.SYNOPSIS
VMs creation.
.DESCRIPTION
Create multiple VMs on the vCenter.
.NOTES
File name : Create-VM.ps1
Author : Pierre JACQUOT
Date : 20/06/2017
Version : 1.0
.LINK
Website : https://www.pierrejacquot.yo.fr
Reference : https://www.pierrejacquot.yo.fr/index.php/scripts/42-script-create-vm
#>
Clear-Host
## Log files creation ##
Function Write-Log([string]$Output, [string]$Message) {
Write-Verbose $Message
((Get-Date -UFormat "[%d-%m-%Y %H:%M:%S] ") + $Message) | Out-File -FilePath $Output -Append -Force
}
## List of variables ##
$StartTime = Get-Date
$Hostname = [Environment]::MachineName
$FullLogin = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Login = [Environment]::UserName
$Workfolder = Split-Path $script:MyInvocation.MyCommand.Path
$Date = Get-Date -UFormat "%Y-%m-%d"
$LogFile = $Workfolder + "\Logs\$Date-Create-VMs.log"
$TargetOU = "Path of your OU. Example : OU=Servers,DC=test,DC=local"
## Collect information from XML ##
$xml = [xml](Get-Content -Path ".\XML\VM-Configuration.xml")
$Node = $xml.selectnodes("//CreateVM/VM")
$VMNumber = $Node.Count
## Title of the script ##
Write-Host "############################################################################"
Write-Host "# Script : Create-VM | Version : 1.0 | Date : $Date #"
Write-Host "############################################################################"
Write-Host "`r"
## Importing Active Directory module for Windows PowerShell ##
$Module = Get-Module -List ActiveDirectory
Import-Module ActiveDirectory -ErrorAction SilentlyContinue
If (!$Module) {
Write-Host "[ERROR] Unable to locate Active Directory module for Windows PowerShell" -ForegroundColor Red
Write-Log -Output $LogFile -Message "[ERROR] Unable to locate Active Directory module for Windows PowerShell"
Exit
}
Write-Host "Launching the creation of [$VMNumber] Virtual Machine(s)." -ForegroundColor Cyan
Write-Log -Output $LogFile -Message "Launching the creation of $VMNumber Virtual Machine(s)"
Write-Host "`r"
## Connect to the vCenter ##
Try {
Write-Host "Trying to connect on VMware Server..."
Write-Host "`r"
Write-Log -Output $LogFile -Message "Trying to connect on VMware Server..."
$Connection = Connect-VIServer -Server vCenterServerName
}
Catch {
Write-Host "[ERROR] Unable to connect on VMware Server" -ForegroundColor Red
Write-Log -Output $LogFile -Message "[ERROR] Unable to connect on VMware Server"
Write-Host "`r"
"`r" | Out-File -FilePath $LogFile -Append -Force
Exit
}
Write-Host "Connected on the vCenter [$Connection] :" -ForegroundColor Green
Write-Host "- From [$Hostname]" -ForegroundColor Green
Write-Host "- With [$FullLogin]" -ForegroundColor Green
Write-Host "`r"
Write-Log -Output $LogFile -Message "Connected on the vCenter $Connection :"
Write-Log -Output $LogFile -Message "- From : $Hostname"
Write-Log -Output $LogFile -Message "- With : $FullLogin"
## Ask your password to add the VM(s) in Active Directory ##
Write-Log -Output $LogFile -Message "Ask your admin password to add the VM(s) in Active Directory"
Write-Host "- Set your admin password to add the VM(s) in Active Directory :" -ForegroundColor Cyan
Write-Host "`r"
Do {
$Pass = Read-Host "- Set your admin password [$FullLogin] " -AsSecureString
$Password = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pass))
If ($Password -eq "") {
Write-Host " Password is mandatory !" -ForegroundColor Red
Write-Host "`r"
}
} Until ($Password -ne "")
Write-Host "`r"
## Process the XML file ##
ForEach ($vm in $xml.CreateVM.VM) {
$VMName = $vm.VMName
$Template = $vm.Template
$Datacenter = $vm.Datacenter
$Cluster = $vm.Cluster
$ESX = $vm.ESX
$Datastore = $vm.Datastore
$Drive = $vm.Drive
$Drive2 = $vm.Drive2
$Drive3 = $vm.Drive3
$DiskStorageFormat = "Thick"
$CPU = $vm.CPU
$Memory = $vm.MemoryGB
$VLAN = $vm.VLAN
$IP = $vm.IP
$Mask = $vm.Mask
$Gateway = $vm.Gateway
$DNS = $($vm.DNS).split(" ")
$Description = $vm.Description
$TSEADGroup = "GRP_"+$VMName+"_TSE"
$ADMADGroup = "GRP_"+$VMName+"_ADM"
$TSEADGroupDescription = "Groupe des utilisateurs ayant des droits d'accès à distance sur $VMName"
$ADMADGroupDescription = "Groupe des administrateurs locaux de $VMName"
Try {
## Collect information of the XML file ##
Write-Log -Output $LogFile -Message "Creation of the log file :"
Write-Log -Output $LogFile -Message "- Path : $Workfolder\Logs"
Write-Log -Output $LogFile -Message "- File name : $Date-Create-VMs.log"
Write-Log -Output $LogFile -Message "Configuration of the XML file :"
Write-Log -Output $LogFile -Message "#############################################"
Write-Log -Output $LogFile -Message "- Hostname : $VMName"
Write-Log -Output $LogFile -Message "- Template : $Template"
Write-Log -Output $LogFile -Message "- Datacenter : $Datacenter"
Write-Log -Output $LogFile -Message "- Cluster : $Cluster"
Write-Log -Output $LogFile -Message "- ESX : $ESX"
Write-Log -Output $LogFile -Message "- Datastore : $Datastore"
Write-Log -Output $LogFile -Message "- Drive (GB) : $Drive"
Write-Log -Output $LogFile -Message "- Drive2 (GB) : $Drive2"
Write-Log -Output $LogFile -Message "- Drive3 (GB) : $Drive3"
Write-Log -Output $LogFile -Message "- CPU : $CPU"
Write-Log -Output $LogFile -Message "- Memory (GB) : $Memory"
Write-Log -Output $LogFile -Message "- VLAN : $VLAN"
Write-Log -Output $LogFile -Message "- IP : $IP"
Write-Log -Output $LogFile -Message "- Mask : $Mask"
Write-Log -Output $LogFile -Message "- Gateway : $Gateway"
Write-Log -Output $LogFile -Message "- DNS : $DNS"
Write-Log -Output $LogFile -Message "- VM Description : $Description"
Write-Log -Output $LogFile -Message "#############################################"
Write-Host "- Creation of the VM [$VMName] started :" -ForegroundColor Green
Write-Log -Output $LogFile -Message "Creation of the VM $VMName started :"
## Collect information of the datastore ##
$Datastores = Get-Datastore $Datastore
$Spacefree = [Math]::round($Datastores[0].FreeSpaceMB / 1024)
$DatastoreName = $Datastores[0].Name
Write-Host " Datastore [$DatastoreName] selected -> [$Spacefree GB] free space" -ForegroundColor Cyan
Write-Log -Output $LogFile -Message "- Datastore $DatastoreName selected -> $Spacefree (GB) free space"
$TotalDriveNeeded = ([int]$Drive + [int]$Drive2 + [int]$Drive3)
Write-Host " Space needed for the VM creation : [$TotalDriveNeeded GB]" -ForegroundColor Cyan
Write-Log -Output $LogFile -Message "- Space needed for the VM creation : $TotalDriveNeeded (GB)"
If ($TotalDriveNeeded -ge $Spacefree) {
Write-Host " Not enough space on [$Datastore]. Please free up some space or create another Datastore !" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Not enough space on $DatastoreName datastore !"
"`r" | Out-File -FilePath $LogFile -Append -Force
Write-Host "`r"
Exit
}
## Ask the local admin password of the VM ##
Write-Log -Output $LogFile -Message "- Ask the local admin password on $VMName"
Write-Host " Set the local admin password on [$VMName]" -ForegroundColor Cyan
Write-Host "`r"
Do {
$AdminPass = Read-Host "- Set the local admin password on [$VMName] " -AsSecureString
$AdminPassword = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($AdminPass))
If ($AdminPassword -eq "") {
Write-Host " Password is mandatory !" -ForegroundColor Red
Write-Host "`r"
}
} Until ($AdminPassword -ne "")
Write-Host "`r"
## Select the right template ##
$Template = Get-Template -Location $Datacenter | ? { $_.Name -like $Template }
Write-Host " Using [$Template] template" -ForegroundColor Cyan
Write-Log -Output $LogFile -Message "- Using $Template template"
## Cloning the template ##
$ResourcePool = Get-Cluster -Location $Datacenter -Name $Cluster
Try {
Write-Host " Cloning [$Template] template" -ForegroundColor Green
New-VM -VMHost $ESX -Name $VMName -Template $Template -Datastore $Datastore -ResourcePool $ResourcePool -Description $Description -ErrorAction Stop | Out-Null
Write-Log -Output $LogFile -Message "- Cloning $Template template"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to clone [$Template] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to clone $Template : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
## Setting the VM (Hostname, CPU, RAM) ##
Try {
Write-Host " Setting Hostname, CPU and RAM on [$VMName]" -ForegroundColor Green
Set-VM -VM $VMName -Name $VMName -NumCpu $CPU -MemoryGB $Memory -Confirm:$false -ErrorAction Stop | Out-Null
Write-Log -Output $LogFile -Message "- Setting Hostname, CPU and RAM on $VMName"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to configure [$VMName] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to configure $VMName : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
## Setting up disk(s) space ##
$vmToChange = Get-VM -Name $VMName
If ($Drive -gt 40) {
Try {
Get-HardDisk -VM $vmToChange | ? {$_.CapacityGB -like "40"} | Set-HardDisk -CapacityGB $Drive -Confirm:$false -ErrorAction Stop | Out-Null
Write-Host " Extend done on the first virtual disk. Please extend the disk in Windows !" -ForegroundColor Yellow
Write-Log -Output $LogFile -Message "- Setting first virtual disk size to $Drive (GB)"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to resize the first virtual disk on [$VMName] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to resize the first virtual disk on $VMName : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
}
If ($Drive2 -gt 10) {
Try {
Get-HardDisk -VM $vmToChange | ? {$_.CapacityGB -like "10"} | Set-HardDisk -CapacityGB $Drive2 -Confirm:$false -ErrorAction Stop | Out-Null
Write-Host " Extend done on the second virtual disk. Please extend the disk in Windows !" -ForegroundColor Yellow
Write-Log -Output $LogFile -Message "- Setting second virtual disk size to $Drive2 (GB)"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to resize the second virtual disk on [$VMName] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to resize the second virtual disk on $VMName : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
}
## Add a third virtual disk ##
If ($Drive3 -gt 0) {
Try {
$vmToChange | New-HardDisk -CapacityGB $Drive3 -StorageFormat $DiskStorageFormat -Confirm:$false -ErrorAction Stop | Out-Null
Write-Host " Third virtual disk with [$Drive3 GB] added. Please initialize the disk in Windows !" -ForegroundColor Yellow
Write-Log -Output $LogFile -Message "- Third virtual disk with $Drive3 (GB) added. Please initialize the disk in Windows !"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to add the third virtual disk on [$VMname] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to add the third virtual disk on $VMname : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
}
## Setting the VM (VLAN) ##
Try {
Write-Host " Setting the VM [$VMName] on VLAN [$VLAN]" -ForegroundColor Green
Get-VM -Name $VMName | Get-NetworkAdapter | Set-NetworkAdapter -Type "Vmxnet3" -NetworkName $VLAN -StartConnected:$true -Confirm:$false –ErrorAction Stop | Out-Null
Write-Log -Output $LogFile -Message "- Setting the VM $VMName on VLAN $VLAN"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to set network card : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to set network card : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
## Customizing VM ##
Try {
$OSCustSpec = New-OSCustomizationSpec -Name $VMName -NamingScheme Fixed -NamingPrefix $VMName -OSType Windows -FullName Name -OrgName "OrgName" -ChangeSid -Domain "DomainName" -DomainUsername $Login -DomainPassword $Password -AdminPassword $AdminPassword -TimeZone 105
Write-Host " Applying customization on [$VMName]" -ForegroundColor Green
$OSCustSpec | Get-OSCustomizationNicMapping | Set-OSCustomizationNicMapping -IpMode UseStaticIp -IpAddress $IP -SubnetMask $Mask -DefaultGateway $Gateway -DNS $DNS | Out-null
Set-VM -VM $VMName -OSCustomizationSpec $OSCustSpec -Confirm:$false | Out-Null
Get-OSCustomizationSpec -Name $VMName | Remove-OSCustomizationSpec -Confirm:$false | Out-null
Write-Log -Output $LogFile -Message "- Applying customization on $VMName"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to apply customization on [$VMName] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to apply customization on $VMName : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
## Power ON the VM ##
Try {
Write-Host "`r"
Write-Host "- Power ON the VM [$VMName]" -ForegroundColor Green
Start-VM -VM $VMname –ErrorAction Stop | Out-Null
Write-Log -Output $LogFile -Message "Power ON the VM $VMName"
Write-Host "`r"
Write-Host "After starting, the VM will be restarted several times in order to finalize customization. Please don't touch the VM until everything is done." -ForegroundColor Red -BackgroundColor Yellow
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host "- [ERROR] Unable to start the VM [$VMName] : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to start the VM $VMName : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
Continue
}
## Creation of AD groups (TSE, ADM) ##
Write-Host "`r"
Write-Host "- Creation of AD groups started :" -ForegroundColor Green
Write-Log -Output $LogFile -Message "Creation of AD groups :"
## AD group creation (TSE) ##
Try {
New-ADGroup -Name $TSEADGroup -GroupScope Global -Description $TSEADGroupDescription -Path $TargetOU
Write-Host " AD group [$TSEADGroup] created" -ForegroundColor Green
Write-Log -Output $LogFile -Message "- AD group $TSEADGroup created - Groupe des utilisateurs ayant des droits d'accès à distance sur $VMName"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to create the group $TSEADGroup on AD : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to create the group $TSEADGroup on AD : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
}
## AD group creation (ADM) ##
Try {
New-ADGroup -Name $ADMADGroup -GroupScope Global -Description $ADMADGroupDescription -Path $TargetOU
Write-Host " AD group [$ADMADGroup] created" -ForegroundColor Green
Write-Log -Output $LogFile -Message "- AD group $ADMADGroup created - Groupe des administrateurs locaux de $VMName"
"`r" | Out-File -FilePath $LogFile -Append -Force
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host " [ERROR] Unable to create the group $ADMADGroup on AD : $ErrorMessage" -ForegroundColor Red
Write-Log -Output $LogFile -Message "- [ERROR] Unable to create the group $ADMADGroup on AD : $ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
}
Write-Host "`r"
Write-Host "Please move the server to the right folder/OU !" -ForegroundColor Yellow
Write-Host "Please add AD groups (TSE & ADM) in the VM !" -ForegroundColor Yellow
Write-Host "`r"
}
Catch {
$ErrorMessage = $_.Exception.Message
Write-Host "$ErrorMessage" -ForegroundColor Red
Write-Log -Output "$LogFile" -Message "$ErrorMessage"
"`r" | Out-File -FilePath $LogFile -Append -Force
}
}
Write-Host "`r"
Disconnect-VIServer -Server * -Force -Confirm:$false
Write-Host "Disconnecting of VMware Server" -ForegroundColor Green
Write-Host "`r"
$EndTime = Get-Date
$Duration = [math]::Round((New-TimeSpan -Start $StartTime -End $EndTime).TotalMinutes,2)
Write-Host "`r"
Write-Host "Script launched from : " -NoNewline; Write-Host $Hostname -ForegroundColor Red
Write-Host "By : " -NoNewline; Write-Host $FullLogin -ForegroundColor Red
Write-Host "Path : " -NoNewline; Write-Host $Workfolder -ForegroundColor Red
Write-Host "Start time : " -NoNewline; Write-Host $StartTime -ForegroundColor Red
Write-Host "End time : " -NoNewline; Write-Host $EndTime -ForegroundColor Red
Write-Host "Duration : " -NoNewline; Write-Host $Duration -ForegroundColor Red -nonewline; Write-Host " minutes"
Write-Host "`r"
Exemple du fichier Create-VM.log
créé automatiquement avec la configuration complète des VMs :
[21-06-2017 10:41:47] Launching the creation of 1 Virtual Machine(s) [21-06-2017 10:41:47] Trying to connect on VMware Server... [21-06-2017 10:41:49] Connected on the vCenter SRVVCENTER : [21-06-2017 10:41:49] - From : LAPTOP-P0L4K [21-06-2017 10:41:49] - With : laptop-p0l4k\Pierre [21-06-2017 10:41:49] Ask your admin password to add the VM(s) in Active Directory [21-06-2017 10:44:55] Creation of the log file : [21-06-2017 10:44:55] - Path : E:\Scripts\Create-VM\Logs [21-06-2017 10:44:55] - File name : 2017-06-21-Create-VMs.log [21-06-2017 10:44:55] Configuration of the XML file : [21-06-2017 10:44:55] ############################################# [21-06-2017 10:44:55] - Hostname : DEVPARADM01 [21-06-2017 10:44:55] - Template : Modèle 2012 R2 [21-06-2017 10:44:55] - Datacenter : DCName [21-06-2017 10:44:55] - Cluster : DEV [21-06-2017 10:44:55] - ESX : ESXName [21-06-2017 10:44:55] - Datastore : TEST_AUTO_VM_DC1_C2 [21-06-2017 10:44:55] - Drive (GB) : 40 [21-06-2017 10:44:55] - Drive2 (GB) : 20 [21-06-2017 10:44:55] - Drive3 (GB) : 0 [21-06-2017 10:44:55] - CPU : 2 [21-06-2017 10:44:55] - Memory (GB) : 4 [21-06-2017 10:44:55] - VLAN : LAN_Dev [21-06-2017 10:44:55] - IP : 192.XXX.XXX.XXX [21-06-2017 10:44:55] - Mask : 255.255.255.0 [21-06-2017 10:44:55] - Gateway : 192.XXX.XXX.XXX [21-06-2017 10:44:55] - DNS : 8.8.8.8 8.8.4.4 [21-06-2017 10:44:55] - VM Description : ADM Server 01 on DEV [21-06-2017 10:44:55] ############################################# [21-06-2017 10:44:55] Creation of the VM DEVPARADM01 started : [21-06-2017 10:44:55] - Datastore TEST_AUTO_VM_DC1_C2 selected -> 199 (GB) free space [21-06-2017 10:44:55] - Space needed for the VM creation : 60 (GB) [21-06-2017 10:44:55] - Ask the local admin password on DEVPARADM01 [21-06-2017 10:48:42] - Using Modèle 2012 R2 template [21-06-2017 10:51:19] - Cloning Modèle 2012 R2 template [21-06-2017 10:51:23] - Setting Hostname, CPU and RAM on DEVPARADM01 [21-06-2017 10:51:29] - Setting second virtual disk size to 20 (GB) [21-06-2017 10:51:32] - Setting the VM DEVPARADM01 on VLAN LAN_Dev [21-06-2017 10:51:44] - Applying customization on DEVPARADM01 [21-06-2017 10:51:47] Power ON the VM DEVPARADM01 [21-06-2017 10:51:47] Creation of AD groups : [21-06-2017 10:51:47] - AD group GRP_DEVPARADM01_TSE created - Groupe des utilisateurs ayant des droits d'accès à distance sur DEVPARADM01 [21-06-2017 10:51:47] - AD group GRP_DEVPARADM01_ADM created - Groupe des administrateurs locaux de DEVPARADM01
Cliquer ici pour télécharger le script.
- Détails
- Écrit par Pierre JACQUOT
- Catégorie : Scripts
- Affichages : 123
Ce script créé par mes soins permet de lister l'ensemble des alertes actives sur le vCenter et d'envoyer le résultat par mail sous la forme d'un rapport.
Fonctionnalités :
- Lister l'ensemble des alertes actives sur le vCenter
- Envoyer un rapport par mail uniquement s'il existe au moins une alerte sur le vCenter afin de limiter les mails
Prérequis :
- Avoir les droits administrateur sur la plateforme VMware
- Installer la dernière version des VMware PowerCLI
Utilisation :
- Compléter les variables suivantes dans le script :
- $vCenter = "vCenterServerName" (Serveur vCenter)
- $MailFrom = "UserName[at]mail.fr" (Adresse mail de l'expéditeur)
- $MailTo = "UserName[at]mail.fr" (Adresse mail du destinataire)
- $MailCc = "UserName[at]mail.fr" (Adresse mail de la personne à mettre en copie)
- $MailSMTPServer = "SMTPServerName" (Serveur SMTP)
Screenshot :
Code du script :
<#
.SYNOPSIS
Retrieves alerts on your VMware vCenter Server.
.DESCRIPTION
Retrieves and send by e-mail all alerts on your VMware vCenter Server.
.NOTES
File name : Get-Alerts.ps1
Author : Pierre JACQUOT
Date : 30/05/2016
Version : 1.0
.LINK
Website : https://www.pierrejacquot.yo.fr
Reference : https://www.pierrejacquot.yo.fr/index.php/scripts/41-script-get-alerts
#>
Clear-Host
# List of variables
$StartTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[string]$Hostname = [Environment]::MachineName
[string]$Login = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
[string]$Workfolder = Split-Path $MyInvocation.MyCommand.Path
[string]$Date = Get-Date -UFormat "%Y-%m-%d"
[string]$CSVFile = $Workfolder + "\$Date-Alerts-Export.csv"
[string]$ReportFile = $Workfolder + "\$Date-Alerts-Report.html"
[string]$vCenter = "vCenterServerName"
[string]$Table = $Null
[System.Collections.ArrayList]$AlertList = @()
Write-Host "Get-Alerts :" -ForegroundColor Black -BackgroundColor Yellow
# Trying to connect to the VMware vCenter Server
Try {
$Connexion = Connect-VIServer -Server $vCenter
Write-Host "Connected on the VMware vCenter Server : $Connexion" -ForegroundColor Green
}
Catch {
Write-Host "[ERROR] : Unable to connect on the VMware vCenter Server" -ForegroundColor Red
Exit
}
# Retrieves and count alert(s) on the VMware vCenter Server
$rootFolder = Get-Folder -NoRecursion
$Alerts = ($rootFolder.ExtensionData.TriggeredAlarmState) | Sort-Object Time -Descending | Select-Object *
[int]$AlertsNumber = $Alerts.Count
If ($AlertsNumber -ge 1) {
# Send-MailMessage parameters
[string]$MailFrom = "vCenter[at]mail.fr"
[string]$MailTo = @('UserName[at]mail.fr')
[string]$MailCc = @('UserName[at]mail.fr')
[string]$MailSubject = "[$Date] - [VMware] - Alert(s) daily report on : $vCenter"
[string]$MailSMTPServer = "SMTPServerName"
[string]$MailBody = '<html>'
$MailBody += '<head>'
$MailBody += "<title>$MailSubject</title>"
$MailBody += '<style type="text/css">'
$MailBody += 'h1 { font-family: Arial; color: #e68a00; font-size: 28px; }'
$MailBody += 'h2 { font-family: Arial; color: #000000; font-size: 16px; }'
$MailBody += '.customTable { border: 1px solid #000000; }'
$MailBody += '.customTable table { border-collapse: collapse; border-spacing: 0; margin: 0px; padding: 0px; }'
$MailBody += '.customTable th { background-color: #d3e5d4; font-size: 14px; font-family: Arial; font-weight: bold; }'
$MailBody += '.customTable td { font-size: 13px; font-family: Arial; }'
$MailBody += '.customTable tr:nth-child(even) { background-color: #f0f0f2; }'
$MailBody += '.customTable tr:hover { background-color: #ddd; }'
$MailBody += '.CriticalStatus { background-color: #ff0000; font-weight: bold; color: #ffffff; }'
$MailBody += '.WarningStatus { background-color: #ffa500; font-weight: bold; color: #ffffff; }'
$MailBody += '#PostInfo { font-family: Arial; font-size: 11px; font-style: italic; }'
$MailBody += 'span.Info { color: #000099; }'
$MailBody += '</style>'
$MailBody += '</head>'
$MailBody += '<body>'
$MailBody += "<h1>$MailSubject</h1>"
$MailBody += "<h2>Number of alert(s) : <span class='Info'>$AlertsNumber</span></h2>"
# Prepare Table
$Table += '<table class="customTable">'
$Table += "<tr><th>Time</th><th>EntityType</th><th>Entity</th><th>Alarm</th><th>Acknowledged</th><th>AckBy</th><th>AckTime</th><th>Status</th></tr>"
Foreach ($Alert in $Alerts) {
[string]$AlarmAlarm = (Get-View $Alert.Alarm).Info.Name
[string]$AlarmEntity = (Get-View $Alert.Entity).Name
[string]$AlarmEntityType = (Get-View $Alert.Entity).GetType().Name
$AlarmTime = $Alert.Time
[string]$AlarmAcknowledged = $Alert.Acknowledged
If ($AlarmAcknowledged -eq "True" ) {
$AlarmAcknowledged = "Yes"
}
Else {
$AlarmAcknowledged = "No"
}
[string]$AlarmAckBy = $Alert.AcknowledgedByUser
$AlarmAckTime = $Alert.AcknowledgedTime
[string]$AlarmStatus = $Alert.OverallStatus
If ($AlarmStatus -eq "red" ) {
$AlarmStatus = "Alert"
}
Else {
$AlarmStatus = "Warning"
}
$Table += "<tr><td>$AlarmTime</td><td>$AlarmEntityType</td><td>$AlarmEntity</td><td>$AlarmAlarm</td><td>$AlarmAcknowledged</td><td>$AlarmAckBy</td><td>$AlarmAckTime</td><td>$AlarmStatus</td></tr>"
$ServerObject = [PSCustomObject]@{
Time = $AlarmTime
EntityTime = $AlarmEntityType
Entity = $AlarmEntity
Alarm = $AlarmAlarm
Acknowledged = $AlarmAcknowledged
AckBy = $AlarmAckBy
AckTime = $AlarmAckTime
Status = $AlarmStatus
}
$AlertList.Add($ServerObject) | Out-Null
}
$Table += "</table>"
$AlertList | Export-Csv -Path $CSVFile -NoTypeInformation -Delimiter ";" -Encoding UTF8
$EndTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[decimal]$Duration = [math]::Round((New-TimeSpan -Start $StartTime -End $EndTime).TotalSeconds,2)
[string]$Info = "<p id='PostInfo'>Script launched from : <span class='Info'>$Hostname</span><br/>
By : <span class='Info'>$Login</span><br/>
Path : <span class='Info'>$Workfolder</span><br/>
CSV file : <span class='Info'>$(Split-Path $CSVFile -Leaf)</span><br/>
Report file : <span class='Info'>$(Split-Path $ReportFile -Leaf)</span><br/>
Start time : <span class='Info'>$StartTime</span><br/>
End time : <span class='Info'>$EndTime</span><br/>
Duration : <span class='Info'>$Duration</span> second(s)</p>"
$MailBody += $Table
$MailBody += $Info
$MailBody += '</body>'
$MailBody += '</html>'
$MailBody = $MailBody -replace '<td>Warning</td>','<td class="WarningStatus">Warning</td>'
$MailBody = $MailBody -replace '<td>Alert</td>','<td class="CriticalStatus">Alert</td>'
$MailBody | Out-File -FilePath $ReportFile
$AlertList | Format-Table
Try {
Send-MailMessage -From $MailFrom -To $MailTo -Cc $MailCc -Subject $MailSubject -Body $MailBody -Priority High -Attachments $ReportFile -SmtpServer $MailSMTPServer -BodyAsHtml -Encoding UTF8
Write-Host "VMware alerts(s) report with attached file : $(Split-Path $ReportFile -Leaf) has been sent by e-mail" -ForegroundColor Green
}
Catch {
[string]$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage -ForegroundColor Red
}
Disconnect-VIServer -Server $vCenter -Confirm:$false
}
Else {
Disconnect-VIServer -Server $vCenter -Confirm:$false
}
Write-Host "`r"
Write-Host "Script launched from : " -NoNewline; Write-Host $Hostname -ForegroundColor Red
Write-Host "By : " -NoNewline; Write-Host $Login -ForegroundColor Red
Write-Host "Path : " -NoNewline; Write-Host $Workfolder -ForegroundColor Red
Write-Host "CSV file : " -NoNewline; Write-Host (Split-Path $CSVFile -Leaf) -ForegroundColor Red
Write-Host "Report file : " -NoNewline; Write-Host (Split-Path $ReportFile -Leaf) -ForegroundColor Red
Write-Host "Start time : " -NoNewline; Write-Host $StartTime -ForegroundColor Red
Write-Host "End time : " -NoNewline; Write-Host $EndTime -ForegroundColor Red
Write-Host "Duration : " -NoNewline; Write-Host $Duration -ForegroundColor Red -nonewline; Write-Host " second(s)"
Write-Host "`r"
Il ne reste plus qu'à planifier l'exécution du script via un ordonnanceur.
Cliquer ici pour visualiser un exemple du rapport Alerts-Report.html
créé automatiquement.
Cliquer ici pour télécharger le script.
- Détails
- Écrit par Pierre JACQUOT
- Catégorie : Scripts
- Affichages : 100
Ce script créé par mes soins permet de lister l'ensemble des snapshots existants sur le vCenter et d'envoyer le résultat par mail sous la forme d'un rapport.
Fonctionnalités :
- Lister l'ensemble des snapshots existants sur le vCenter
- Envoyer un rapport par mail uniquement s'il existe au moins un snapshot sur le vCenter afin de limiter les mails
Prérequis :
- Avoir les droits administrateur sur la plateforme VMware
- Installer la dernière version des VMware PowerCLI
Utilisation :
- Compléter les variables suivantes dans le script :
- $vCenter = "vCenterServerName" (Serveur vCenter)
- $MailFrom = "UserName[at]mail.fr" (Adresse mail de l'expéditeur)
- $MailTo = "UserName[at]mail.fr" (Adresse mail du destinataire)
- $MailCc = "UserName[at]mail.fr" (Adresse mail de la personne à mettre en copie)
- $MailSMTPServer = "SMTPServerName" (Serveur SMTP)
Screenshot :
Code du script :
<#
.SYNOPSIS
Retrieves VM snapshots on your VMware vCenter Server.
.DESCRIPTION
Retrieves and send by e-mail all VM snapshots on your VMware vCenter Server.
.NOTES
File name : Get-Snapshots.ps1
Author : Pierre JACQUOT
Date : 30/05/2016
Version : 1.0
.LINK
Website : https://www.pierrejacquot.yo.fr
Reference : https://www.pierrejacquot.yo.fr/index.php/scripts/40-script-get-snapshots
#>
Clear-Host
# List of variables
$StartTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[string]$Hostname = [Environment]::MachineName
[string]$Login = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
[string]$Workfolder = Split-Path $MyInvocation.MyCommand.Path
[string]$Date = Get-Date -UFormat "%Y-%m-%d"
[string]$CSVFile = $Workfolder + "\$Date-Snapshots-Export.csv"
[string]$ReportFile = $Workfolder + "\$Date-Snapshots-Report.html"
[string]$vCenter = "vCenterServerName"
[string]$Table = $Null
Write-Host "Get-Snapshots :" -ForegroundColor Black -BackgroundColor Yellow
# Trying to connect to the VMware vCenter Server
Try {
$Connexion = Connect-VIServer -Server $vCenter
Write-Host "Connected on the VMware vCenter Server : $Connexion" -ForegroundColor Green
}
Catch {
Write-Host "[ERROR] : Unable to connect on the VMware vCenter Server" -ForegroundColor Red
Exit
}
# Retrieves and count VM snapshot(s) on the VMware vCenter Server
[array]$Snapshots = (Get-VM | Get-Snapshot | Sort-Object Created -Descending | Select-Object VM, @{Name="SizeGB";Expression={"{0:N2}" -f $_.SizeGB}}, Created, Name, Description)
[int]$SnapshotsNumber = $Snapshots.Count
If ($SnapshotsNumber -ge 1) {
# Send-MailMessage parameters
[string]$MailFrom = "vCenter[at]mail.fr"
[string]$MailTo = @('UserName[at]mail.fr')
[string]$MailCc = @('UserName[at]mail.fr')
[string]$MailSubject = "[$Date] - [VMware] - Snapshot(s) daily report on : $vCenter"
[string]$MailSMTPServer = "SMTPServerName"
[string]$MailBody = '<html>'
$MailBody += '<head>'
$MailBody += "<title>$MailSubject</title>"
$MailBody += '<style type="text/css">'
$MailBody += 'h1 { font-family: Arial; color: #e68a00; font-size: 28px; }'
$MailBody += 'h2 { font-family: Arial; color: #000000; font-size: 16px; }'
$MailBody += '.customTable { border: 1px solid #000000; }'
$MailBody += '.customTable table { border-collapse: collapse; border-spacing: 0; margin: 0px; padding: 0px; }'
$MailBody += '.customTable th { background-color: #d3e5d4; font-size: 14px; font-family: Arial; font-weight: bold; }'
$MailBody += '.customTable td { font-size: 13px; font-family: Arial; }'
$MailBody += '.customTable tr:nth-child(even) { background-color: #f0f0f2; }'
$MailBody += '.customTable tr:hover { background-color: #ddd; }'
$MailBody += '#PostInfo { font-family: Arial; font-size: 11px; font-style: italic; }'
$MailBody += 'span.Info { color: #000099; }'
$MailBody += '</style>'
$MailBody += '</head>'
$MailBody += '<body>'
$MailBody += "<h1>$MailSubject</h1>"
$MailBody += "<h2>Number of snapshot(s) : <span class='Info'>$SnapshotsNumber</span></h2>"
# Prepare Table
$Table += '<table class="customTable">'
$Table += "<tr><th>VM</th><th>SizeGB</th><th>Created</th><th>Name</th><th>Description</th></tr>"
Foreach ($Snapshot in $Snapshots) {
[string]$SnapVM = ($Snapshot.VM).Name
$SnapSizeGB = "{0:N2}" -f $Snapshot.SizeGB
$SnapCreated = $Snapshot.Created
[string]$SnapName = $Snapshot.Name
[string]$SnapDescription = $Snapshot.Description
$Table += "<tr><td>$SnapVM</td><td>$SnapSizeGB</td><td>$SnapCreated</td><td>$SnapName</td><td>$SnapDescription</td></tr>"
}
$Table += "</table>"
$Snapshots | Export-Csv -Path $CSVFile -NoTypeInformation -Delimiter ";" -Encoding UTF8
$EndTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
[decimal]$Duration = [math]::Round((New-TimeSpan -Start $StartTime -End $EndTime).TotalSeconds,2)
[string]$Info = "<p id='PostInfo'>Script launched from : <span class='Info'>$Hostname</span><br/>
By : <span class='Info'>$Login</span><br/>
Path : <span class='Info'>$Workfolder</span><br/>
CSV file : <span class='Info'>$(Split-Path $CSVFile -Leaf)</span><br/>
Report file : <span class='Info'>$(Split-Path $ReportFile -Leaf)</span><br/>
Start time : <span class='Info'>$StartTime</span><br/>
End time : <span class='Info'>$EndTime</span><br/>
Duration : <span class='Info'>$Duration</span> second(s)</p>"
$MailBody += $Table
$MailBody += $Info
$MailBody += '</body>'
$MailBody += '</html>'
$MailBody | Out-File -FilePath $ReportFile
$Snapshots | Format-Table
Try {
Send-MailMessage -From $MailFrom -To $MailTo -Cc $MailCc -Subject $MailSubject -Body $MailBody -Priority High -Attachments $ReportFile -SmtpServer $MailSMTPServer -BodyAsHtml -Encoding UTF8
Write-Host "VM snapshot(s) report with attached file : $(Split-Path $ReportFile -Leaf) has been sent by e-mail" -ForegroundColor Green
}
Catch {
[string]$ErrorMessage = $_.Exception.Message
Write-Host $ErrorMessage -ForegroundColor Red
}
Disconnect-VIServer -Server $vCenter -Confirm:$false
}
Else {
Disconnect-VIServer -Server $vCenter -Confirm:$false
}
Write-Host "`r"
Write-Host "Script launched from : " -NoNewline; Write-Host $Hostname -ForegroundColor Red
Write-Host "By : " -NoNewline; Write-Host $Login -ForegroundColor Red
Write-Host "Path : " -NoNewline; Write-Host $Workfolder -ForegroundColor Red
Write-Host "CSV file : " -NoNewline; Write-Host (Split-Path $CSVFile -Leaf) -ForegroundColor Red
Write-Host "Report file : " -NoNewline; Write-Host (Split-Path $ReportFile -Leaf) -ForegroundColor Red
Write-Host "Start time : " -NoNewline; Write-Host $StartTime -ForegroundColor Red
Write-Host "End time : " -NoNewline; Write-Host $EndTime -ForegroundColor Red
Write-Host "Duration : " -NoNewline; Write-Host $Duration -ForegroundColor Red -nonewline; Write-Host " second(s)"
Write-Host "`r"
Il ne reste plus qu'à planifier l'exécution du script via un ordonnanceur.
Cliquer ici pour visualiser un exemple du rapport Snapshots-Report.html
créé automatiquement.
Cliquer ici pour télécharger le script.
Page 1 sur 3