Have a Question?
< All Topics

How to connect to vCenter 6.7 via REST API using PowerShell

Steps to connect to vCenter 6.7 via REST API using PowerShell

Prepare a MasterKey & Password file in C:\Scripts

We can copy the entire folder to another computer and run it without needing to reenter password again

$KeyFile = "C:\Scripts\MasterKey.key"
$PasswordFile = "C:\Scripts\VC-Password.txt"

$Key = New-Object Byte[] 32
$Key | out-file $KeyFile

#Enter your username & Password when prompt and save the password you enter to $passwordfile
(get-credential).Password | ConvertFrom-SecureString -key (get-content $KeyFile) | set-content $PasswordFile

Enter Username & Password in the popup box

$KeyFile = "C:\Scripts\MasterKey.key"
$PasswordFile = "C:\Scripts\VC-Password.txt"

$Password = Get-Content $PasswordFile | ConvertTo-SecureString -Key (Get-Content $KeyFile)
$UserName = "[email protected]" 
$credential = New-Object System.Management.Automation.PsCredential($UserName,$Password)

Prepare the Authentication Header

#Generate Auth
$auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($Credential.UserName+':'+$Credential.GetNetworkCredential().Password))
$head = @{
  'Authorization' = "Basic $auth"

Include the codes below if Selfsign Certificate is used

#Ignore SelfSign Cert 
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
$certCallback = @"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
        public static void Ignore()
            if(ServicePointManager.ServerCertificateValidationCallback ==null)
                ServicePointManager.ServerCertificateValidationCallback += 
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                        return true;
    Add-Type $certCallback

Replace the $VCSA_IP with the real IP and connect to vCenter REST API

#Connect to VCSA 
$VCSA_IP = ""
$RestApi = Invoke-WebRequest -Uri https://$VCSA_IP/rest/com/vmware/cis/session -Method Post -Headers $head
$token = (ConvertFrom-Json $RestApi.Content).value
$session = @{'vmware-api-session-id' = $token}

List all VMs provisioned

#List All 
$R1 = Invoke-WebRequest -Uri https://teraju-vcsa.teraju.local/rest/vcenter/vm -Method Get -Headers $session
$vms = (ConvertFrom-Json $R1.Content).value
Table of Contents
Scroll to Top