Ok, the following should handle all cases.
Note that the call to the UpdateAuthorizationRole method might return sooner than the changes are actually applied.
When checking via the Web Client make sure to refresh the page.
$Pfile = .\Folder\Plist.txt
$PList = Import-Csv -Path $Pfile
$privs = Get-VIPrivilege -Id $PList.LIST
$authMgr = Get-View AuthorizationManager
$sysPrivs = 'System.Anonymous','System.Read','System.View'
$existingRole = Get-VIRole -Name $NewRole -ErrorAction SilentlyContinue
if ($existingRole) {
Write-Host "A role with the name $NewRole already exists."
$currentPrivileges = $existingRole.PrivilegeList | Sort-Object
$missingPrivileges = $PList.LIST | Where-Object { $_ -notin $currentPrivileges }
$extraPrivileges = $existingRole.PrivilegeList | Where-Object { $_ -notin $privs.Id -and $_ -notin $sysPrivs}
if (!$missingPrivileges -and !$extraPrivileges) {
Write-Host "The role $NewRole has the correct privileges:"
} else {
if ($missingPrivileges) {
Write-Host "The role $NewRole is missing the following privileges:"
Write-Host ($missingPrivileges -join "`n")
}
if ($extraPrivileges) {
Write-Host "The role $NewRole the following extra privileges:"
Write-Host ($extraPrivileges -join "`n")
}
# Correct the privileges
$authMgr.UpdateAuthorizationRole($existingRole.Id, $existingRole.Name, $privs.Id)
Write-Host "The role $NewRole now has the correct privileges:"
}
} else {
New-VIRole -Name $NewRole -Privilege $privs
}