At work, there was a requirement to upload an ISO to the vSphere Content Library in an automated fashion (no GUI).
With PowerCLI 11, New-ContentLibrary commandlet seemed to do the job and creates and uploads the ISO file.
However, it creates and uploads the file as type: ‘file’
1 |
New-ContentLibraryItem -ContentLibrary vgnosis_cl -Name $item -Files $file_name |
As you can see below type=’file’
If the item is of type ‘file’, it can’t be mounted to VMs (CD Drive)
Also, there is no option to change the type of the file with the PowerCLI Content Library commandlets.
Therefore, I used a combination of PowerCLI (to upload) and REST API (to modify the type), as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
#variables $vcenter = 'vCenter FQDN' $item = 'name of the ISO' $file_name = 'location of the iso file' #Get credentials $Credential = Get-Credential #Connect to vCenter Connect-VIServer $vcenter -Credential $Credential #Upload the ISO and store its id to a variable New-ContentLibraryItem -ContentLibrary {{CONTENTLIBRARYNAME}} -Name $item -Files $file_name $cl_id = Get-ContentLibraryItem -Name $item | Select-object Id -ExpandProperty id #Determine Authorisation Methods $auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName+':'+$Credential.GetNetworkCredential().Password)) $head = @{ 'Authorization' = "Basic $auth" } #Authenticate against vCenter $r = Invoke-WebRequest -Uri https://$vcenter/rest/com/vmware/cis/session -Method Post -Headers $head $token = (ConvertFrom-Json $r.Content).value $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Content-Type", "application/json") $headers.Add("Authorization", "Basic $token") $headers.Add("vmware-api-session-id", "$token") #define the type of the ISO to be type=iso and use REST to update it $body = "{ `n `"update_spec`": { `n `"type`": `"iso`" `n } `n}" $URI = "https://vgnosisvap06.vgnosis.com/rest/com/vmware/content/library/item/id:$cl_id" $response = Invoke-RestMethod $URI -Method 'PATCH' -Headers $headers -Body $body $response | ConvertTo-Json |
Modify the variables to match your environment.
What the script does:
- Stores information (vcenter, item, location)
- Gets credentials
- connects to vcenter
- Creates and uploads the iso file
- creates an authorized session to REST API
- uses Patch to modify the Content Library Item ID type field to ‘ISO’