NSX, VMware’s network virtualization and security platform, allows you to apply security tags to virtual machines to define and enforce security policies and micro segmentation. Find here below a quick function that simplifies the TAG extraction. It requires only the user, password and uri as input parameters.
It will return an object array of all virtual Machines managed by NSX. This object also contains information about TAGs. The script will also handle pagination (the REST call returns 1000 results per page).
Tested on PowerShell 7 & NSX 4.1.
GitHub: https://github.com/maxioio/powershell_shorties
$username = "nsx-user"
$pass = Read-Host "Enter password" -AsSecureString
$mgr = "https://my-nsx-manager.com"
$vmarray = @()
# Function to extract
FUNCTION get-NSXvmTags(){
param(
$username,
$pass,
$mgr
)
$vmarray = @()
$cursor = $null
$targeturi = "/api/v1/fabric/virtual-machines"
$uri = $mgr + $targeturi
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
$userpass = $username + ":" + $password
$bytes= [System.Text.Encoding]::UTF8.GetBytes($userpass)
$encodedlogin=[Convert]::ToBase64String($bytes)
$authheader = "Basic " + $encodedlogin
$header = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$header.Add("Authorization",$authheader)
$res = Invoke-RestMethod -Uri $uri -Headers $header -Method 'GET'
$vmarray += $res.results
$cursor = $res.cursor
Write-Host($vmarray.count)
while ($cursor -ne $null) {
$targeturi = "/api/v1/fabric/virtual-machines"
if ($cursor -ne $null) {
$targeturi += "?cursor=" + $cursor
}
$uri = $mgr + $targeturi
$res = Invoke-RestMethod -Uri $uri -Headers $header -Method 'GET'
$vmarray += $res.results
$cursor = $res.cursor
}
return $vmarray
}
$vmarray = get-NSXvmTags $username $pass $mgr