public/Remove-VPASEPVGroup.ps1

<#
.Synopsis
   DELETE EPV GROUP
   CREATED BY: Vadim Melamed, EMAIL: vmelamed5@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO DELETE 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
   Define the method by which the EPV groups will be queried by
   Possible values: GroupName, GroupID
.PARAMETER GroupLookupVal
   Search value that will be used to query for target EPV group
.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-VPASEPVGroup -GroupLookupBy GroupName -GroupLookupVal {GROUPNAME VALUE} -WhatIf
.EXAMPLE
   $DeleteEPVGroupStatus = Remove-VPASEPVGroup -GroupLookupBy GroupName -GroupLookupVal {GROUPNAME VALUE}
.EXAMPLE
   $DeleteEPVGroupStatus = Remove-VPASEPVGroup -GroupLookupBy GroupID -GroupLookupVal {GROUPID VALUE}
.OUTPUTS
   $true if successful
   $false if failed
#>

function Remove-VPASEPVGroup{
    [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=$false,ValueFromPipelineByPropertyName=$true,Position=2)]
        [hashtable]$token,

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

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

    )

    Begin{
        $tokenval,$sessionval,$PVWA,$Header,$ISPSS,$IdentityURL,$EnableTextRecorder,$AuditTimeStamp,$NoSSL,$VaultVersion,$HideWarnings,$AuthenticatedAs,$SubDomain = 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"

        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"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$PVWA/PasswordVault/api/UserGroups/$GroupID"
            }
            $log = Write-VPASTextRecorder -inputval $uri -token $token -LogType URI
            $log = Write-VPASTextRecorder -inputval "DELETE" -token $token -LogType METHOD

            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
                    $WhatIfGroupMembers = $WhatIfGroup.members
                    $WhatIfGroupGroupName = $WhatIfGroup.groupName
                    $WhatIfGroupDescription = $WhatIfGroup.description
                    $WhatIfGroupLocation = $WhatIfGroup.location

                    if($WhatIfGroupID -eq $GroupID){
                        #AFFECTED MEMBERS
                        $WhatIfMembers = @()
                        foreach($mem in $WhatIfGroupMembers){
                            $targetuser = $mem.username
                            $targetid = $mem.id
                            $minihash = @{
                                username = $targetuser
                                id = $targetid
                            }
                            $WhatIfMembers += $minihash
                        }

                        #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 -token $token -HideWarning

                            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 GROUP WOULD BE DELETED:" -type S
                            Write-VPASOutput -str "ID : $WhatIfGroupID" -type S
                            Write-VPASOutput -str "GroupType : $WhatIfGroupGroupType" -type S
                            Write-VPASOutput -str "Members : $WhatIfMembers" -type S
                            Write-VPASOutput -str "GroupName : $WhatIfGroupGroupName" -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
                                Members = $WhatIfMembers
                                GroupName = $WhatIfGroupGroupName
                                Description = $WhatIfGroupDescription
                                Location = $WhatIfGroupLocation
                                NumberOfAffectedSafes = $WhatIfAffectedSafesCount
                                AffectedSafes = $WhatIfAffectedSafes
                                NumberOfAffectedAccounts = $WhatIfAffectedAccountsCounter
                                AffectedAccounts = $WhatIfAffectedAccounts
                                RestURI = $uri
                                RestMethod = "DELETE"
                                Disclaimer = "THIS EPV GROUP WILL BE DELETED 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...RETURNING FALSE" -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{
                Write-Verbose "MAKING API CALL TO CYBERARK"

                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 $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 $GroupLookupBy : $GroupLookupVal"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}