Skip to content

New-Template

VMware: Creates a new virtual machine template

#Requires -Version 5.1
#Requires -Modules VMware.VimAutomation.Core
[CmdletBinding(DefaultParameterSetName = "byName")]
Param(
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$VIServer,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [pscredential]$VICredential,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$TemplateName,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [string]$VMId,
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$VMName,
    [Parameter(Mandatory = $true, ParameterSetName = "byID")]
    [Parameter(Mandatory = $true, ParameterSetName = "byName")]
    [string]$Datacenter
)
Process {
    try {
        $vmServer = Connect-VIServer -Server $VIServer -Credential $VICredential -ErrorAction Stop
        if ($PSCmdlet.ParameterSetName -eq "byID") { $machine = Get-VM -Server $vmServer -Id $VMId -ErrorAction Stop }
        else { $machine = Get-VM -Server $vmServer -Name $VMName -ErrorAction Stop }
        $center = Get-Datacenter -Name $Datacenter -Server $vmServer -ErrorAction Stop
        $result = New-Template -Name $TemplateName -VM $machine -Location $center -Server $vmServer -Confirm:$false -ErrorAction Stop | Select-Object *
        if ($null -ne $result) { $result | Add-Member -NotePropertyName Timestamp -NotePropertyValue (Get-Date -Format "yyyy-MM-dd HH:mm:ss") -PassThru -Force }
    }
    catch { throw }
    finally { if ($null -ne $vmServer) { Disconnect-VIServer -Server $vmServer -Force -Confirm:$false -ErrorAction SilentlyContinue } }
}

IP address or DNS name of the vSphere server

PSCredential object for authenticating with the server

Name of the new template

ID of the source virtual machine

Name of the source virtual machine

Datacenter where to place the new template

An interactive directory of PowerShell scripts.