public/Remove-VPASMemberEPVGroup.ps1

<#
.Synopsis
   DELETE MEMBER FROM EPV GROUP
   CREATED BY: Vadim Melamed, EMAIL: vmelamed5@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO DELETE A MEMBER FROM AN EPV GROUP
.PARAMETER token
   HashTable of data containing various pieces of login information (PVWA, LoginToken, HeaderType, etc).
   If -token is not passed, function will use last known hashtable generated by New-VPASToken
.PARAMETER GroupLookupBy
   Specify method to query for target EPVGroup
   Possible values: GroupName, GroupID
.PARAMETER GroupLookupVal
   Search value to query for target EPVGroup
.PARAMETER EPVUserName
   Target EPVUserName that will be removed from target EPVGroup
.PARAMETER WhatIf
   Run code simulation to see what is affected by running the command as well as any possible implications
   This is a code simulation flag, meaning the command will NOT actually run
.PARAMETER HideWhatIfOutput
   Suppress any code simulation output from the console
.EXAMPLE
   $WhatIfSimulation = Remove-VPASMemberEPVGroup -GroupLookupBy GroupName -GroupLookupVal {GROUPNAME VALUE} -EPVUserName {USERNAME VALUE} -WhatIf
.EXAMPLE
   $DeleteMemberEPVGroupStatus = Remove-VPASMemberEPVGroup -GroupLookupBy GroupName -GroupLookupVal {GROUPNAME VALUE} -EPVUserName {USERNAME VALUE}
.EXAMPLE
   $DeleteMemberEPVGroupStatus = Remove-VPASMemberEPVGroup -GroupLookupBy GroupID -GroupLookupVal {GROUPID VALUE} -EPVUserName {USERNAME VALUE}
.OUTPUTS
   $true if successful
   $false if failed
#>

function Remove-VPASMemberEPVGroup{
    [OutputType([bool],'System.Object')]
    [CmdletBinding()]
    Param(

        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="Enter search method (GroupName, GroupID)",Position=0)]
        [ValidateSet('GroupName','GroupID')]
        [String]$GroupLookupBy,

        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="Enter search value to query target EPVGroup",Position=1)]
        [String]$GroupLookupVal,

        [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,HelpMessage="Enter EPVUser to remove from EPVGroup",Position=2)]
        [String]$EPVUserName,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=3)]
        [hashtable]$token,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=4)]
        [Switch]$WhatIf,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=5)]
        [Switch]$HideWhatIfOutput

    )

    Begin{
        $tokenval,$sessionval,$PVWA,$Header,$ISPSS,$IdentityURL,$EnableTextRecorder,$AuditTimeStamp,$NoSSL,$VaultVersion = Get-VPASSession -token $token
        $CommandName = $MyInvocation.MyCommand.Name
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType COMMAND
    }
    Process{
        Write-Verbose "SUCCESSFULLY PARSED PVWA VALUE"
        Write-Verbose "SUCCESSFULLY PARSED TOKEN VALUE"
        Write-Verbose "SUCCESSFULLY PARSED GROUPLOOKUPBY VALUE: $GroupLookupBy"
        Write-Verbose "SUCCESSFULLY PARSED GROUPLOOKUPVALUE VALUE: $GroupLookupVal"
        Write-Verbose "SUCCESSFULLY PARSED EPVUSERNAME VALUE: $EPVUserName"

        try{

            if($GroupLookupBy -eq "GroupName"){
                Write-Verbose "CONSTRUCTING SEARCH STRING TO QUERY CYBERARK"
                $searchQuery = "$GroupLookupVal"
                Write-Verbose "INVOKING HELPER FUNCTION TO RETRIEVE GROUPID"

                $GroupID = Get-VPASEPVGroupIDHelper -token $token -GroupName $GroupLookupVal
            }
            elseif($GroupLookupBy -eq "GroupID"){
                Write-Verbose "SUPPLIED GROUPID, SKIPPING HELPER FUNCTION"
                $GroupID = $GroupLookupVal
            }

            if($NoSSL){
                Write-Verbose "NO SSL ENABLED, USING HTTP INSTEAD OF HTTPS"
                $uri = "http://$PVWA/PasswordVault/api/UserGroups/$GroupID/Members/$EPVUserName/"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$PVWA/PasswordVault/api/UserGroups/$GroupID/Members/$EPVUserName/"
            }
            $log = Write-VPASTextRecorder -inputval $uri -token $token -LogType URI
            $log = Write-VPASTextRecorder -inputval "DELETE" -token $token -LogType METHOD

            Write-Verbose "MAKING API CALL TO CYBERARK"

            if($WhatIf){
                $log = Write-VPASTextRecorder -token $token -LogType WHATIF1
                $WhatIfHash = @{}
                Write-Verbose "INITIATING COMMAND SIMULATION"

                $WhatIfInfo = Get-VPASAllEPVGroups -IncludeMembers -token $token

                foreach($WhatIfGroup in $WhatIfInfo.value){
                    $WhatIfGroupID = $WhatIfGroup.id
                    $WhatIfGroupGroupType = $WhatIfGroup.groupType
                    $WhatIfGroupGroupName = $WhatIfGroup.groupName
                    $WhatIfGroupDescription = $WhatIfGroup.description
                    $WhatIfGroupLocation = $WhatIfGroup.location
                    $WhatIfGroupTargetUser = $false
                    $WhatIfGroupTargetID = $false
                    $WhatIfGroupMembers = $WhatIfGroup.members

                    if($WhatIfGroupID -eq $GroupID){
                        #AFFECTED MEMBER
                        foreach($mem in $WhatIfGroupMembers){
                            $targetuser = $mem.username
                            $targetid = $mem.id
                            if($targetuser -eq $EPVUserName){
                                $WhatIfGroupTargetUser = $targetuser
                                $WhatIfGroupTargetID = $targetid
                            }
                        }
                        if(!$WhatIfGroupTargetUser){
                            $log = Write-VPASTextRecorder -inputval "UNABLE TO FIND $EPVUserName IN GROUP ID" -token $token -LogType MISC
                            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                            $log = Write-VPASTextRecorder -token $token -LogType WHATIF2
                            Write-Verbose "UNABLE TO FIND $EPVUserName IN GROUP ID...RETURNING FALSE"
                            Write-VPASOutput "UNABLE TO FIND $EPVUserName IN GROUP ID...RETURNING FALSE" -type E
                            return $false
                        }

                        #AFFECTED SAFES
                        $WhatIfAffectedSafesCount = 0
                        $WhatIfAffectedSafes = @()
                        $CheckSafes = Get-VPASAllSafes -token $token

                        foreach($safe in $CheckSafes.value){
                            $CheckSafeName = $safe.safeName

                            $CheckTargetGroup = Get-VPASSafeMemberSearch -safe $CheckSafeName -member $WhatIfGroupGroupName -token $token 6> $null
                            if($CheckTargetGroup){
                                $WhatIfAffectedSafesCount += 1
                                $WhatIfAffectedSafes += $CheckSafeName
                            }
                        }

                        #AFFECTED ACCOUNTS
                        $WhatIfAffectedAccountsCounter = 0
                        $WhatIfAffectedAccounts = @()
                        foreach($safe in $WhatIfAffectedSafes){
                            $miniHash = @{}

                            $AffectedAccounts = Get-VPASAccountDetails -safe $safe -HideWarnings -token $token

                            foreach($AffectedAcct in $AffectedAccounts.value){
                                $AffectedAcctSafe = $AffectedAcct.safeName
                                if($AffectedAcctSafe -eq $safe){
                                    $WhatIfAffectedAccountsCounter += 1
                                    $miniHash = @{
                                        SafeName = $AffectedAcct.safeName
                                        ID = $AffectedAcct.id
                                        Address = $AffectedAcct.address
                                        Username = $AffectedAcct.userName
                                        Name = $AffectedAcct.name
                                    }
                                    $WhatIfAffectedAccounts += $miniHash
                                }
                            }
                        }

                        if(!$HideWhatIfOutput){
                            Write-VPASOutput -str "====== BEGIN COMMAND SIMULATION ======" -type S
                            Write-VPASOutput -str "THE FOLLOWING EPV USER WILL BE REMOVED FROM THIS EPV GROUP:" -type S
                            Write-VPASOutput -str "ID : $WhatIfGroupID" -type S
                            Write-VPASOutput -str "GroupType : $WhatIfGroupGroupType" -type S
                            Write-VPASOutput -str "GroupName : $WhatIfGroupGroupName" -type S
                            Write-VPASOutput -str "EPVUser : $WhatIfGroupTargetUser" -type S
                            Write-VPASOutput -str "EPVUserID : $WhatIfGroupTargetID" -type S
                            Write-VPASOutput -str "Description : $WhatIfGroupDescription" -type S
                            Write-VPASOutput -str "Location : $WhatIfGroupLocation" -type S
                            Write-VPASOutput -str "NumberOfAffectedAccounts : $WhatIfAffectedAccountsCounter" -type S
                            Write-VPASOutput -str "AffectedAccounts : $WhatIfAffectedAccounts" -type S
                            Write-VPASOutput -str "NumberOfAffectedSafes : $WhatIfAffectedSafesCount" -type S
                            Write-VPASOutput -str "AffectedSafes : $WhatIfAffectedSafes" -type S
                            Write-VPASOutput -str "---" -type S
                            Write-VPASOutput -str "URI : $uri" -type S
                            Write-VPASOutput -str "METHOD : DELETE" -type S
                            Write-VPASOutput -str " " -type S
                            Write-VPASOutput -str "======= END COMMAND SIMULATION =======" -type S
                        }

                        $WhatIfHash = @{
                            WhatIf = @{
                                ID = $WhatIfGroupID
                                GroupType = $WhatIfGroupGroupType
                                EPVUser = $WhatIfGroupTargetUser
                                EPVUserID = $WhatIfGroupTargetID
                                GroupName = $WhatIfGroupGroupName
                                Description = $WhatIfGroupDescription
                                Location = $WhatIfGroupLocation
                                NumberOfAffectedSafes = $WhatIfAffectedSafesCount
                                AffectedSafes = $WhatIfAffectedSafes
                                NumberOfAffectedAccounts = $WhatIfAffectedAccountsCounter
                                AffectedAccounts = $WhatIfAffectedAccounts
                                RestURI = $uri
                                RestMethod = "DELETE"
                                Disclaimer = "THIS EPV USER WILL BE REMOVED FROM THIS EPV GROUP IF -WhatIf FLAG IS REMOVED"
                                Disclaimer2 = "THIS CODE SIMULATION DOES NOT DIG INTO NESTED GROUPS...YET..."
                            }
                        }
                        $WhatIfJSON = $WhatIfHash | ConvertTo-Json | ConvertFrom-Json
                        $log = Write-VPASTextRecorder -inputval $WhatIfJSON -token $token -LogType RETURNARRAY
                        $log = Write-VPASTextRecorder -token $token -LogType WHATIF2
                        return $WhatIfJSON
                    }
                }
                $log = Write-VPASTextRecorder -inputval "UNABLE TO FIND TARGET EPV GROUP ID" -token $token -LogType MISC
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                $log = Write-VPASTextRecorder -token $token -LogType WHATIF2
                Write-Verbose "UNABLE TO FIND TARGET EPV GROUP ID...RETURNING FALSE"
                Write-VPASOutput "UNABLE TO FIND TARGET EPV GROUP ID" -type E
                return $false
            }
            else{
                if($sessionval){
                    $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method DELETE -ContentType "application/json" -WebSession $sessionval
                }
                else{
                    $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method DELETE -ContentType "application/json"
                }
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: TRUE" -token $token -LogType MISC
                Write-Verbose "SUCCESSFULLY DELETED $EPVUserName FROM $GroupLookupBy : $GroupLookupVal"
                return $true
            }
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "UNABLE TO DELETE $EPVUserName FROM $GroupLookupBy : $GroupLookupVal"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}