Contents

How to connect to vCenter 6.7 via REST API using PowerShell

You are here:
← All Topics

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
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$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 += 
                    delegate
                    (
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                    )
                    {
                        return true;
                    };
            }
        }
    }
"@
    Add-Type $certCallback
 }
[ServerCertificateValidationCallback]::Ignore()

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

#Connect to VCSA 
$VCSA_IP = "192.168.10.224"
$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
$vms
$vms.Count

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top