public/Add-VPASSafe.ps1

<#
.Synopsis
   CREATE SAFE
   CREATED BY: Vadim Melamed, EMAIL: vpasmodule@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO CREATE A SAFE IN CYBERARK
.LINK
   https://vpasmodule.com/commands/Add-VPASSafe
.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 Description
   An explanation/details of the target resource
   Best practice states to leave informative descriptions to help identify the resource purpose
.PARAMETER safe
   Target unique safe name
.PARAMETER passwordManager
   Define which CPM will be assigned to the safe
   A blank value or not passing a CPM will NOT assign a CPM to the safe
.PARAMETER numberOfVersionsRetention
   Define how many versions of passwords will be kept in an accounts history
.PARAMETER numberOfDaysRetention
   Define how many days worth of passwords will be kept in an accounts history
.PARAMETER OLACEnabled
   Define if to turn on OLAC (Object Level Access Control) for the safe'
.PARAMETER InputParameters
   HashTable of values containing the parameters required to make the API call
.EXAMPLE
   $CreateSafeJSON = Add-VPASSafe -safe {SAFE VALUE} -passwordManager {PASSWORDMANAGER VALUE} -OLACEnabled -Description {DESCRIPTION VALUE}
.EXAMPLE
   $InputParameters = @{
        safe = "NewSafe1"
        passwordmanager = "CPMNameHere"
        OLACEnabled = $true|$false
        Description = "Description for new safe here"
        numberOfDaysRetention = 7
   }
   $CreateSafeJSON = Add-VPASSafe -InputParameters $InputParameters
.EXAMPLE
   $InputParameters = @{
        safe = "NewSafe1"
        passwordmanager = "CPMNameHere"
        OLACEnabled = $true|$false
        Description = "Description for new safe here"
        numberOfVersionsRetention = 5
   }
   $CreateSafeJSON = Add-VPASSafe -InputParameters $InputParameters
.OUTPUTS
   If successful:
   {
        "safeUrlId": "NewSafeVpas",
        "safeName": "NewSafeVpas",
        "safeNumber": 133,
        "description": "New safe for documentation purposes",
        "location": "\\",
        "creator": {
                        "id": "8c904dd3-b9f1-4e02-b4b0-8f314bb62f12",
                        "name": "vadim@vman.com"
                    },
        "olacEnabled": false,
        "managingCPM": "ISPSSConnector",
        "numberOfVersionsRetention": null,
        "numberOfDaysRetention": 7,
        "autoPurgeEnabled": false,
        "creationTime": 1723779203,
        "lastModificationTime": 1723779197277627
   }
   ---
   $false if failed
#>

function Add-VPASSafe{
    [OutputType('System.Object',[bool])]
    [CmdletBinding(DefaultParameterSetName='Set1')]
    Param(

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Name of new safe (for example: TestSafe1)")]
        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Name of new safe (for example: TestSafe1)")]
        [String]$safe,

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [Parameter(Mandatory=$false,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true)]
        [String]$passwordManager,

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [ValidateRange(0,999)]
        [Int]$numberOfVersionsRetention,

        [Parameter(Mandatory=$false,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true)]
        [ValidateRange(0,3650)]
        [Int]$numberOfDaysRetention,

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [Parameter(Mandatory=$false,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true)]
        [Switch]$OLACEnabled,

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [Parameter(Mandatory=$false,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true)]
        [String]$Description,

        [Parameter(Mandatory=$true,ParameterSetName='InputParameters',ValueFromPipelineByPropertyName=$true,HelpMessage="Hashtable of parameters required to make API call, refer to get-help -examples for valid inputs")]
        [hashtable]$InputParameters,

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

    Begin{
        $tokenval,$sessionval,$PVWA,$Header,$ISPSS,$IdentityURL,$EnableTextRecorder,$AuditTimeStamp,$NoSSL,$VaultVersion,$HideWarnings,$AuthenticatedAs,$SubDomain,$EnableTroubleshooting = Get-VPASSession -token $token
        $CommandName = $MyInvocation.MyCommand.Name
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType COMMAND
    }
    Process{

        try{
            if($PSCmdlet.ParameterSetName -eq "InputParameters"){
                $KeyHash = @{
                    set1 = @{
                        AcceptableKeys = @("safe","passwordManager","numberOfVersionsRetention","OLACEnabled","Description")
                        MandatoryKeys = @("safe")
                    }
                    set2 = @{
                        AcceptableKeys = @("safe","passwordManager","numberOfDaysRetention","OLACEnabled","Description")
                        MandatoryKeys = @("safe")
                    }
                }
                $CheckSet = Test-VPASHashtableKeysHelper -InputHash $InputParameters -KeyHash $KeyHash

                if(!$CheckSet){
                    $log = Write-VPASTextRecorder -inputval "FAILED TO FIND TARGET PARAMETER SET" -token $token -LogType MISC
                    Write-Verbose "FAILED TO FIND TARGET PARAMETER SET"
                    Write-VPASOutput -str "FAILED TO FIND TARGET PARAMETER SET...VIEW EXAMPLES BELOW:" -type E
                    $examples = Write-VPASExampleHelper -CommandName $CommandName
                    return $false
                }
                else{
                    foreach($key in $InputParameters.Keys){
                        Set-Variable -Name $key -Value $InputParameters.$key
                    }
                }
            }
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "FAILED TO CREATE SAFE"
            Write-VPASOutput -str $_ -type E
            return $false
        }

        #MISC SECTION
        $params = @{}

        $params += @{
            SafeName = $safe
            Description = $Description
        }

        if([String]::IsNullOrEmpty($passwordManager)){
            Write-Verbose "NO CPM USER SPECIFIED, SAFE WILL BE CREATED WITH NO CPM USER ATTACHED"
            Write-VPASOutput -str "NO CPM USER SPECIFIED, SAFE WILL BE CREATED WITH NO CPM USER ATTACHED" -type M
        }
        else{
            $params += @{ ManagingCPM = $passwordManager }
        }

        if($numberOfVersionsRetention -and $numberOfDaysRetention){
            Write-Verbose "BOTH VERSION RETENTION SPECIFIED AS WELL AS DAYS RETENTION, ONLY ONE CAN BE SPECIFIED, DEFAULT VERSION RETENTION SELECTED"
            Write-VPASOutput -str "BOTH VERSION RETENTION SPECIFIED AS WELL AS DAYS RETENTION, ONLY ONE CAN BE SPECIFIED, DEFAULT VERSION RETENTION SELECTED" -type M
            $numberOfDaysRetention = $false
        }

        if(!$numberOfVersionsRetention){
            Write-Verbose "NO VERSION RETENTION SPECIFIED, SAFE WILL BE CREATED WITH DEFAULT VALUE OF 5 VERSIONS"
            Write-VPASOutput -str "NO VERSION RETENTION SPECIFIED" -type M
        }
        else{
            $params += @{ NumberOfVersionsRetention = $numberOfVersionsRetention }
        }

        if(!$numberOfDaysRetention){
            if(!$numberOfVersionsRetention){
                $numberOfDaysRetention = 7
                $params += @{ NumberofDaysRetention = $numberOfDaysRetention }
            }
        }
        else{
            $params += @{ NumberofDaysRetention = $numberOfDaysRetention }
        }

        if(!$OLACEnabled){
            Write-Verbose "NO OLAC SPECIFIED, SAFE WILL BE CREATED WITH DEFAULT VALUE OF false"
            #Write-VPASOutput -str "NO OLAC SPECIFIED, SAFE WILL BE CREATED WITH DEFAULT VALUE OF OLAC SET TO FALSE" -type M
            $OLACEnabledstr = "false"
            $params += @{ OLACEnabled = $OLACEnabledstr }
        }
        else{
            $OLACEnabledstr = "true"
            $params += @{ OLACEnabled = $OLACEnabledstr }
        }

        try{
            Write-Verbose "MAKING API CALL TO CYBERARK"

            if($NoSSL){
                Write-Verbose "NO SSL ENABLED, USING HTTP INSTEAD OF HTTPS"
                $uri = "http://$PVWA/PasswordVault/API/Safes"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$PVWA/PasswordVault/API/Safes"
            }
            $log = Write-VPASTextRecorder -inputval $params -token $token -LogType PARAMS
            $params = $params | ConvertTo-Json

            $log = Write-VPASTextRecorder -inputval $uri -token $token -LogType URI
            $log = Write-VPASTextRecorder -inputval "POST" -token $token -LogType METHOD

            if($sessionval){
                $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method POST -Body $params -ContentType "application/json" -WebSession $sessionval
            }
            else{
                $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method POST -Body $params -ContentType "application/json"
            }
            $log = Write-VPASTextRecorder -inputval $response -token $token -LogType RETURN

            Write-Verbose "PARSING DATA FROM CYBERARK"
            Write-Verbose "RETURNING JSON OBJECT"
            return $response
        }catch{
            $log = Write-VPASTextRecorder -inputval $_ -token $token -LogType ERROR
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "FAILED TO CREATE SAFE IN CYBERARK"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}