Skip to content

Instantly share code, notes, and snippets.

@Satak
Last active June 24, 2020 06:46
Show Gist options
  • Save Satak/3c56504bdcffb18e95e6b841a782a4ca to your computer and use it in GitHub Desktop.
Save Satak/3c56504bdcffb18e95e6b841a782a4ca to your computer and use it in GitHub Desktop.
VMware REST API functions
$username = 'username'
$password = 'password'
$vcenter = 'localhost'
$authURL = "https://$vcenter/rest/com/vmware/cis/session"
$apiBaseURL = "https://$vcenter/rest/vcenter"
$vmAPIURL = $apiBaseURL + '/vm'
$ct = 'application/json'
$sec = ConvertTo-SecureString -AsPlainText $Password -Force
$creds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $sec
# Authenticate
$r = Invoke-RestMethod -Uri $authURL -SkipCertificateCheck -Authentication Basic -Credential $creds -Method Post
$header = @{'vmware-api-session-id' = $r.value }
function Update-CPU {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[string]
$VMId,
[Parameter(Mandatory)]
[int]
$CoresPerSocket,
[Parameter(Mandatory)]
[int]
$Count
)
$body = @{
"spec" = @{
"cores_per_socket" = $CoresPerSocket
"count" = $Count
}
} | ConvertTo-Json
Invoke-WebRequest -Uri $vmAPIURL + "/$($VMId)/hardware/cpu" -Headers $header -SkipCertificateCheck -Method PATCH -Body $body -ContentType $ct
}
function Detach-Disk {
[CmdletBinding()]
param (
[Parameter(Mandatory, ValueFromPipeline)]
[string]
$VMId,
[Parameter(Mandatory, ValueFromPipeline)]
[string]
$DiskId
)
Invoke-RestMethod $vmAPIURL + "/$($VMId)/hardware/disk/$DiskId" -Method Delete -Headers $header -SkipCertificateCheck
}
<#
?filter.power_states.1=POWERED_OFF
&filter.power_states.2=POWERED_OFF
&filter.resource_pools.1=obj-103
&filter.resource_pools.2=obj-103
&filter.clusters.1=obj-103
&filter.clusters.2=obj-103
&filter.datacenters.1=obj-103
&filter.datacenters.2=obj-103
&filter.names.1=string
&filter.names.2=string
&filter.hosts.1=obj-103
&filter.hosts.2=obj-103
&filter.vms.1=obj-103
&filter.vms.2=obj-103
&filter.folders.1=obj-103
&filter.folders.2=obj-103
#>
$vmName = 'xxx'
$queryString = "?filter.names.1=$vmName"
# Get VMs
$vms = Invoke-WebRequest -Uri $vmAPIURL + $queryString -Headers $header -SkipCertificateCheck
$VMId = $vms.value[0].vm
# update cpu
Update-CPU -VMId $VMId -CoresPerSocket 1 -Count 1
# get disks
$disks = Invoke-RestMethod $vmAPIURL + "/$VMId/hardware/disk"
$diskId = $disks.value[1].disk
# Detach-Disk -VMId $VMId -DiskId $diskId
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment