VMをNew-Templateするときディスクフォーマットを指定したい場合の話。
DiskStorageFormatオプションにバグがあるらしく、ディスクフォーマットの指定をするとエラーになる。
なので、回避策としてCLIを通さない方法を作った。(onyxのおかげ。)
$vmNameにインベントリ名を入れればとりあえず動く…はず。
本来はNew-Template一発でいけるけど、DiskStorageFormatオプションではまった。
コード
#VMオブジェクト取得
$vm = Get-VM -Name $vmName
#------バックアップするVMの情報収集------
#diskIDとディスク数
$disks = $vm|Get-harddisk|% {$_.id.split('/')[1]}
$numberOfDisks = @($disks).Length
#フォルダグループ
$ary = $vm|Select FolderId|% {$_.folderid.split('-')}
$folTyp = $ary[0].tostring()
$folVal = $ary[1].tostring() + "-" +$ary[2].tostring()
#データストア
$ary = Get-Datastore -Name $dataStoreName|% {$_.id.split('-')}
$dsTyp = $ary[0].tostring()
$dsVal = $ary[1].tostring() + "-" +$ary[2].tostring()
#HOST
$ary = $vm|Select VmHostId|% {$_.vmhostid.split('-')}
$htTyp = $ary[0].tostring()
$htVal = $ary[1].tostring() + "-" +$ary[2].tostring()
#------テンプレート化設定(VM本体)------
$folder = New-Object VMware.Vim.ManagedObjectReference
$folder.type = $folTyp
$folder.Value = $folVal
$spec = New-Object VMware.Vim.VirtualMachineCloneSpec
$spec.location = New-Object VMware.Vim.VirtualMachineRelocateSpec
$spec.location.datastore = New-Object VMware.Vim.ManagedObjectReference
$spec.location.datastore.type = $dsTyp
$spec.location.datastore.Value = $dsVal
$spec.location.host = New-Object VMware.Vim.ManagedObjectReference
$spec.location.host.type = $htTyp
$spec.location.host.Value = $htVal
$spec.location.disk = New-Object VMware.Vim.VirtualMachineRelocateSpecDiskLocator[] ($numberOfDisks)
#------テンプレート化設定(各ディスク)------
$i=0
foreach($diskNum in $disks){
$spec.location.disk[$i] = New-Object VMware.Vim.VirtualMachineRelocateSpecDiskLocator
$spec.location.disk[$i].diskId = $diskNum
$spec.location.disk[$i].datastore = New-Object VMware.Vim.ManagedObjectReference
$spec.location.disk[$i].datastore.type = $dsTyp
$spec.location.disk[$i].datastore.Value = $dsVal
$spec.location.disk[$i].diskBackingInfo = New-Object VMware.Vim.VirtualDiskFlatVer2BackingInfo
$spec.location.disk[$i].diskBackingInfo.fileName = ""
$spec.location.disk[$i].diskBackingInfo.diskMode = ""
$spec.location.disk[$i].diskBackingInfo.thinProvisioned = $true
$i++
}
$spec.template = $true
$spec.powerOn = $false
#------テンプレート化実行------
$_this = Get-View -Id $vm.id
$_this.CloneVM_Task($folder, "${vmName}", $spec)