PowerCLI

  • 1.  Remove privileges if it's not included in TXT file

    Posted Nov 27, 2023 10:03 AM

    I have already a script that compares existing privileges with a TXT file and adds a missing ones.

    Solved: Cmpare Privilege based on TXT file - VMware Technology Network VMTN

    I have come to the conclusion that there may be privileges already added but not necessary for the role.

    Is there a way to remove privileges that are not mentioned in the text file?



  • 2.  RE: Remove privileges if it's not included in TXT file

    Posted Nov 27, 2023 10:21 AM

    Wouldn't it be a lot easier if you just remove/add the role when it already exists?
    No fiddling with adding/removing proivileges.



  • 3.  RE: Remove privileges if it's not included in TXT file

    Posted Nov 27, 2023 04:25 PM

    I have considered this, but I am aware that the current role may already have assigned users.



  • 4.  RE: Remove privileges if it's not included in TXT file
    Best Answer

    Posted Nov 27, 2023 08:48 PM

    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
    }