First, you have to understand how vCenter Perms work
They start with a Privileges, very granular checkboxes, like "power On Vm" type activities
Then you roll a bunch of those Privileges together into a PrivilegeList and call that a role
Next you Need 2 more things; an account(called a Principal) and a vCenter object (VIObject) like a VM or cluster, or whatever, and you grant a Permission by creating an association of the Role, the Account, and the VIObject.
So a Permission is really more of a query for the association.
I hope this helps to understand why your script is, in part, approaching this incorrectly. Accounts are not a sub of a role, they are an association with a role.
Secondly, you are trying to call cmdlets or functions, I don't think exist, like "Get-ViewRole" & "Get-ViewPermission"
You have to use cmdlets and/or functions that exist and are available to PowerShell.
# CSV output file path
$csvFilePath = "C:\temp\Roles_with_Account_Count.csv"
# Connect to vCenter
$vcenterServer = Read-Host "Enter vCenter Server name or IP address"
$username = Read-Host "Enter vCenter username"
$password = Read-Host -AsSecureString "Enter vCenter password"
try {
Connect-VIServer -Server $vcenterServer -Credential (New-Object System.Management.Automation.PSCredential ($username, $password))
Write-Host "Successfully connected to vCenter $($vcenterServer)." -ForegroundColor Green
}
catch {
Write-Host "Error connecting to vCenter: $($_.Exception.Message)" -ForegroundColor Red
exit
}
$VIPermissions = Get-VIPermission -Server $vcenterServer
$VIRoles = Get-VIRole -Server $vcenterServer | Sort Name
# Create an array to store the role data
$roleData = @()
ForEach($VIRole in $VIRoles){
$roleData += [PSCustomObject]@{
Role = $VIRole.Name
AccountCount = $(($VIPermissions | Where{$_.Role -eq $VIRole.Name}).Count)
}
}
# Disconnect from vCenter
Disconnect-VIServer -Confirm:$false
Write-Host "Disconnected from vCenter." -ForegroundColor Gray
# Export the data to a CSV file
$roleData | Export-Csv -Path $csvFilePath -NoTypeInformation
Write-Host "Exporting Role Complete from $vcenterServer. Results saved to: $csvFilePath" -ForegroundColor Yellow