New-TAGCategory –Name $TAGCategoryName -Description "VMs System Operation TAG" –Cardinality single –EntityType VirtualMachine
Get-TAGCategory -Name $TAGCategoryName | New-TAG -Name $TAGName -Description "$TAGName Virtual Machine"
$TAGNames = @("Windows", "Linux", "Other OS")
$Result=New-TAGAssignment -TAG $TAGName -Entity $vm
#########################################################################################
# Created by: Luciano Patrão and Vladimir Sokol #
# Date: 7th of Jun 2016 #
# Set VMs TAGs by Guest OS #
# Version 7.0 #
#########################################################################################
### vCenter Server IP
$vCenter = 'Add your vCenter IP'
Connect-VIServer $vCenter
### vCenter Server Name(FQNP)
$vCentName = [system.net.dns]::GetHostByAddress($vCenter).hostname
### TAG Category
$TAGCategoryName="Guest OS"
### VM Guest Operation System TAGs
$TAGNames = @("Windows", "Linux", "Other OS")
### Counters for counting Guest OS TAGs
$Counters = New-Object "int32[,]" $TAGNames.Count,2
### Cluster Name
$Cluster = "add your Cluster name" ## If you don't want to run by Cluster, please comment this line
### Mail Data
$MailFrom = "vCenter Report <add your sender email address>"
$MailTo = "Sender Name <add your destination email address>"
$SMTPServer = "add your email smtp server"
$MailSubject = "Guest Os TAG Report "+$vCentName
### Function for highlight table row when mouse pointer is over it
function Set-AlternatingRows {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True)]
[object[]]$HTMLDocument,
[Parameter(Mandatory=$True)]
[string]$CSSEvenClass,
[Parameter(Mandatory=$True)]
[string]$CSSOddClass
)
Begin {
$ClassName = $CSSEvenClass
}
Process {
[string]$Line = $HTMLDocument
$Line = $Line.Replace("<tr>","<tr class=""$ClassName"">")
if ($ClassName -eq $CSSEvenClass) {
$ClassName = $CSSOddClass
}
else {
$ClassName = $CSSEvenClass
}
$Line = $Line.Replace("<table>","<table width=""50%"">")
Return $Line
}
}
cls
write-host "===============================================================================" -foreground Red
write-host "This script is provided as-is, no warranty is provided or implied. The author"
write-host "is NOT responsible for any damages or data loss that may occur through the use"
write-host "of this script. This script is free to use for both personal and business use,"
write-host "however, it may not be sold or included as part of a package that is for sale."
write-host "===============================================================================" -ForegroundColor Black
# Create header of HTML report
$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse; font-family: arial, verdana, sans-serif}
TR:Hover TD {Background-Color: #C1D5F8;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
.odd { background-color:#ffffff; }
.even { background-color:#dddddd; }
H1,H2,H3,H4,H5,H6 {font-family: arial, verdana, sans-serif}
</style>
<title>
License Report
</title>
"@
##################################################################################################################
############################################# TAG Categories ##################################################
##################################################################################################################
#### First we will check if the category already exists, if not we will create a TAG Catergory for our Guest OS VMs
If ( (Get-TAGCategory -Name $TAGCategoryName -ErrorAction SilentlyContinue) -eq $null )
{
Write-Host "No $TAGCategoryName category founded, script will create one." -foreground Red
$ToHTML="<H4>No $TAGCategoryName category founded, script will create one.</H4>"
$Result=New-TAGCategory –Name $TAGCategoryName -Description "VMs System Operation TAG" –Cardinality single –EntityType VirtualMachine
}
else {
Write-Host "### $TAGCategoryName TAG Category founded, no changes needed. ### "
$ToHTML="<H4>$TAGCategoryName TAG Category founded, no changes needed.</H4>"
}
### Check if TAGs exist in TAG Category ###
$TAGs=@(Get-TAG -Category $TAGCategoryName)
$TAGCategory = @()
foreach ($TAGName in $TAGNames)
{
$Details = "" | select "TAG Category Name", "TAG Name", "TAG Newly Created"
$Details."TAG Category Name"=$TAGCategoryName
$Details."TAG Name"=$TAGName
$Details."TAG Newly Created"="NO"
$TAGCategory+=$Details
if (!($TAGName -in $TAGs.Name))
{
$Details."TAG Newly Created"="YES"
Write-Output "TAG $TAGName doesn't exist in category $TAGCategoryName, script will create it now"
$Result = Get-TAGCategory -Name $TAGCategoryName | New-TAG -Name $TAGName -Description "$TAGName Virtual Machine"
}
}
##################################################################################################################
############################################# VMs Guest TAGs #################################################
##################################################################################################################
#### Set by Cluster
$vms = Get-Cluster $Cluster | Get-VM
#### Set by vCenter
#$vms = Get-VM # If you want to use by vCenter Uncomment this line and comment the above line
$counter = 0
#### Set for all VMs in the vCenter
$NewlyTAGgedVms= @()
foreach ($vm in $vms)
{
$Result=Get-TAGAssignment -Category $TAGCategoryName -Entity $vm
if ($Result)
{
# Write-Host $vm "TAGged" $Result.TAG.name
$Counters[ [array]::indexof($TAGNames,$Result.TAG.Name),0]++
}
else
# Virtual machine doesn't have TAG, so let it add one
{
$OSName= ($vm | Get-VIew).summary.config.GuestFullName
$Details = "" | Select "VM Name", "OS", "TAG Name"
$Details."VM Name" = $vm.Name
$Details.OS = $OSName
$TAGged=$false
# loop through all TAGs for virtual machines
foreach ($TAGName in $TAGNames)
{
if ($OSName -match $TAGname)
# part of guest OS name is in name of TAG for virtual machines
{
Write-Host $vm "no TAG founded, add TAG to VM" $TAGName
$Result=New-TAGAssignment -TAG $TAGName -Entity $vm
$TAGged=$true
$Counters[ [array]::indexof($TAGNames,$TAGName),1]++
$Details."TAG Name" = $TAGName
}
}
if (!$TAGged)
# Guest OS name doesn't have any match with name of TAG for virtual machines
{
Write-Host -NoNewline $vm "no TAG founded, add TAG to VM "
if ($OSName -match "CentOS")
{
# exception: CentOS is Linux that has no word "Linux"in its name
Write-Host "Linux"
$Result=New-TAGAssignment -TAG "Linux" -Entity $vm
$Counters[ [array]::indexof($TAGNames,"Linux"),1]++
$Details."TAG Name" = "Linux"
}
else
{
Write-Host $TAGnames[$TAGNames.Count -1]
# set TAG name to the last name in array of TAG names
$Result=New-TAGAssignment -TAG $TAGNames[$TAGNames.Count -1] -Entity $vm
$Counters[($TAGNames.Count-1),1]++
$Details."TAG Name" = $TAGNames[$TAGNames.Count -1]
}
}
$NewlyTAGgedVms+=$Details
}
$counter++
Write-Progress -Activity 'Processing VMs' -CurrentOperation $VM -PercentComplete (($counter / $VMs.count) * 100)
Start-Sleep -Milliseconds 200
}
#### Number of VMs calculation ####
$Summary=@()
$TotalVMsAlready=0
$TotalVMSNewly=0
for ($i=0; $i -lt $TAGNames.Count; $i++)
{
$Details = "" | Select OS, "Already TAGged", "Newly TAGged"
$Details.OS=$TAGNames[$i]
$Details."Already TAGged"=$Counters[$i,0]
$Details."Newly TAGged"=$Counters[$i,1]
$TotalVMsAlready+=$Details."Already TAGged"
$TotalVMSNewly+=$Details."Newly TAGged"
$Summary+=$Details
}
Write-Host "`n### SUMMARY ###"
$totalVMs=($Counters|Measure-Object -Sum).sum
Write-Host "Founded $totalVMs VMs total"
$Summary | Format-Table -AutoSize
##################################################################################################################
############################################# Generate HTML #################################################
##################################################################################################################
$TAGCategory = $TAGCategory | ConvertTo-Html -PreContent "<H4>$TAGCategoryName TAG Category and its TAG Names:</H4>" -Fragment
if ($NewlyTAGgedVms)
{
$NewlyTAGgedVms = $NewlyTAGgedVms | ConvertTo-Html -PreContent "<H4>Report for Newly assigned TAGs to VMs:</H4>" -Fragment
}
else
{
$NewlyTAGgedVms = "<H4>There is no newly TAGged VMs.</H4>"
}
$Summary = $Summary | ConvertTo-HTML -PreContent "<H4>Summary Report for $TAGCategoryName TAG Category:</H4>" -PostContent "<H4>Total number of VMs: $totalVMs ($TotalVMsAlready already TAGged, $TotalVMsNewly newly TAGged).</H4>" -Fragment
$Report = ConvertTo-Html -Head $Header -Body "$ToHTML $TAGCategory $NewlyTAGgedVms $Summary" | Set-AlternatingRows -CSSEvenClass even -CSSOddClass odd
##################################################################################################################
########################################## Save report to disk ################################################
##################################################################################################################
$ThisDate = Get-Date -format yyyy_MM_dd-HH_mm_ss
$Path=$PSScriptRoot
$GuestOSTAGFile = "$Path\GuestOSTAGs_Report_$vCentName-$ThisDate.html"
$Report | Out-File $GuestOSTAGFile
##################################################################################################################
########################################### Send report by mail ################################################
##################################################################################################################
Write-Host -NoNewline "Sending HTML report by mail to $MailTo ... "
$MailSplat = @{
To = $MailTo
From = $MailFrom
Subject = $MailSubject
Body = ($Report | Out-String)
BodyAsHTML = $true
Attachments = $GuestOSTAGFile
SMTPServer = $SMTPServer
}
Send-MailMessage @MailSplat
Write-Host -ForegroundColor Green "done"
Write-Host "`nGuest OS TAG report in HTML is saved as $GuestOSTAGFile"
Disconnect-VIServer -Server $vCenter -Force -Confirm:$false
Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.
Comments (0)