I have a csv file listing template names. I want to verify they are templates before I run a process to convert to VM, storage vmotion, and convert back to a template (scripted).
$TEMPLATES = (Get-Content "C:\Users\jm\Desktop\template2convert.csv")
Foreach($TEMPLATE in $TEMPLATES) {
# Validate Template (make sure it still exists)
try{
Write-Host ("Validate template: '" + $TEMPLATE + "'")
Get-Template $TEMPLATE
Write-Host -foregroundcolor "green" "Template: $TEMPLATE is valid"
}
catch{
Write-Host -foregroundcolor "red" "Template: $TEMPLATE is invalid"
$valid = $false
}
I get the following. Ideally, I'd like to get:
1. The green font item on the screen.
2. Errors of template names to a txt file for me to deal with separately.
I plan on integrating the list test to the following (feel free to offer tidier coding suggestions as always) so that we may retire a datastore:
# Load PowerCLI cmdlets
Add-PSSnapin TEMPLATEware.VimAutomation.Core -ErrorAction "SilentlyContinue"
$TEMPLATES = (Get-Content "C:\Users\jm\Desktop\template2convert.csv")
Foreach($TEMPLATE in $TEMPLATES) {
Write-Host ("Start Template conversion for TEMPLATE '" + $TEMPLATE + "'")
# Start conversion
Write-Host (Get-Template $TEMPLATE) -ForegroundColor Blue
Write-Host ("Set " + $TEMPLATE + " to VM")
Set-Template -Template $TEMPLATE -ToVM
Write-Host (Get-VM $TEMPLATE | select Name,@{E={$_.ExtensionData.Config.Files.VmPathName};L="VM Path"}) -ForegroundColor Blue
$Cluster = Get-VM $TEMPLATE | Get-Cluster
Write-Host $Cluster
Write-Host (Get-VM $TEMPLATE| Move-VM -Datastore (Get-Cluster $Cluster| Get-Datastore st074no_templates_ds01))
Write-Host (Get-VM $TEMPLATE | select Name,@{E={$_.ExtensionData.Config.Files.VmPathName};L="VM Path"}) -ForegroundColor Green
Get-VM $TEMPLATE | Set-VM -ToTemplate -Confirm:$False
write-Host (Get-Template $TEMPLATE) -ForegroundColor Green
Write-Host ("Template conversion for template '" + $TEMPLATE + "' finished. LOOK FOR ERRORS IN RED Font") -ForegroundColor Magenta
}
The Get-Template failure to find a Template by name is not a terminating exception.
Your catch block will never be reached.
Just add the ErrorAction to force it to become a terminating exception.
try{
Write-Host ("Validate template: '" + $TEMPLATE + "'")
Get-Template $TEMPLATE -ErrorAction Stop
Write-Host -foregroundcolor "green" "Template: $TEMPLATE is valid"
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
The Get-Template failure to find a Template by name is not a terminating exception.
Your catch block will never be reached.
Just add the ErrorAction to force it to become a terminating exception.
try{
Write-Host ("Validate template: '" + $TEMPLATE + "'")
Get-Template $TEMPLATE -ErrorAction Stop
Write-Host -foregroundcolor "green" "Template: $TEMPLATE is valid"
}
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference