Using PowerCLi to Export and Import OS Customization Specs

I was asked to find a solution to automate importing OS customization Specs to our Vcenters. Its a task that not difficult but better if was scripted. I found this code located at ForwardorReverse blog. Export function allows you to export the OS customization Spec to $secname.xml and the import allows you to import them. These two functions are few years old according to the Blog but still work on Vsphere 6.5 without issue.


Function Export-OSCustomizationSpec {
    param (
        [string]$specName,
        [string]$exportFile = "$specname.xml"
    )
    $csmgr = Get-View CustomizationSpecManager
 
    if ($csmgr.DoesCustomizationSpecExist($specName)) {
        $spec = $csmgr.GetCustomizationSpec($specName)
        $csmgr.CustomizationSpecItemToXml($spec) | Out-File $exportFile
    }
    else {
        throw "Spec $specName not found"
    }
}
 
Function Import-OSCustomizationSpec {
    param (
        [string]$importFile,
        [string]$specName #Use to change the spec name from that defined in the file
    )
    $specXml = Get-Content $importFile
    $csmgr = Get-View CustomizationSpecManager
    $spec = $csmgr.XmlToCustomizationSpecItem($specXml)
     # Change the name if a new one was given.
    if ($specName) {
        $spec.Info.Name = $specName
    }
     if ($csmgr.DoesCustomizationSpecExist($spec.Info.Name)) {
        throw "Spec $specName already exists."
    }
    else {
        $csmgr.CreateCustomizationSpec($spec)
    }
}