NSX PowerCLI Basics
NSX PowerCLI Code
Some basic PowerCLI commands with NSX
Included some examples of code to Automate adding/removing NSX Security Tags from VMs.
- Show Security TAGs.
- Show Security TAGs assigned to a specific VM.
Hope you find these snippets of code useful.
# Need to install PowerShell Module PowerNSX
# Connect to vCenter
$vCenterName = 'vCenter.vCrocs.info'
Connect-VIServer $vCenterName -Credential $cred
# Connect to NSX Server
Connect-NsxServer -vCenterServer 'vCenter.vCrocs.info' -Credential $cred
# Show all Security Tags
Get-NsxSecurityTag | Select-Object Name | Sort-Object Name
# Info about one specific Security TAG
Get-NsxSecurityTag -Name NSX.TAG.VMware.vRA.DB
# Get VM Count for a security TAG
$VMcount = Get-NsxSecurityTag -Name NSX.TAG.VMware.vRA.DB
$VMcount.vmCount
# Count One Liner
Get-NsxSecurityTag -Name NSX.TAG.VMware.vRA.DB | Select-Object vmCount
# Show All TAGS assigned to a single VM
Get-VM VM01 | Get-NsxSecuritytagassignment | select-object @{Name="SecurityTag"; expression = {$_.securitytag.name}}, VirtualMachine
# Show All NSX TAGs and all assigned VMs
Get-NsxSecurityTag | Get-NsxSecurityTagAssignment | select-object @{Name="SecurityTag"; expression = {$_.securitytag.name}}, VirtualMachine
# Show TAG and all assigned VMs
Get-NsxSecurityTag | where-object { $_.name -like "*NSX.TAG.VMware.vRA.DB*" } | Get-NsxSecurityTagAssignment | select-object @{Name="SecurityTag"; expression = {$_.securitytag.name}}, VirtualMachine | Format-Table -AutoSize
# Show VM and All TAGS
Get-VM VM01 | Get-NsxSecuritytagassignment | select-object @{Name="SecurityTag"; expression = {$_.securitytag.name}}, VirtualMachine
# Assign a TAG to a VM
Get-VM VM01 | New-NsxSecurityTagAssignment -ApplyTag -SecurityTag (Get-NsxSecurityTag NSX.TAG.VMware.vRA.DB.01)
Get-VM VM01 | New-NsxSecurityTagAssignment -ApplyTag -SecurityTag (Get-NsxSecurityTag NSX.TAG.VMware.vRA.DB.02)
# Remove a TAG from a VM
Get-VM VM01 | Get-NsxSecuritytagassignment | Where-Object {$_.securitytag.name -like '*NSX.TAG.VMware.vRA.DB.01*'} | Remove-NsxSecurityTagAssignment -Confirm:$false
Get-VM VM01 | Get-NsxSecuritytagassignment | Where-Object {$_.securitytag.name -like '*NSX.TAG.VMware.vRA.DB.02*'} | Remove-NsxSecurityTagAssignment -Confirm:$false
Disconnect-VIServer * -Force -Confirm:$false
Disconnect-NsxServer