public/Add-VPASAccount.ps1

<#
.Synopsis
   CREATE ACCOUNT
   CREATED BY: Vadim Melamed, EMAIL: vpasmodule@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO CREATE A NEW ACCOUNT IN CYBERARK
.LINK
   https://vpasmodule.com/commands/Add-VPASAccount
.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 username
   Username that will be assigned to the new account
.PARAMETER platformID
   PlatformID that will be assigned to the new account
.PARAMETER safeName
   SafeName that will be assigned to the new account
.PARAMETER name
   ObjectName that will be assigned to the new account
.PARAMETER address
   Address that will be assigned to the new account
.PARAMETER secretType
   Type of secret that will be assigned to the new account
   Possible values: Password, Key
.PARAMETER secret
   Secret that will be assigned to the new account
.PARAMETER accessRestrictedToRemoteMachines
   Limit if the new account can only connect to specific remote machines
   Possible values: TRUE, FALSE
.PARAMETER remoteMachines
   Specific remote machines that the new account can connect to
.PARAMETER automaticManagementEnabled
   Enable for the account to be automatically managed by the CPM depending on platform settings and configurations
   Possible values: TRUE, FALSE
.PARAMETER manualManagementReason
   Specify a reason for automatic management to be disabled
.PARAMETER extraProps
   Include extra properties that can be defined based on platform settings and configurations
   Pass extra properties in a hashtable following this pattern: @{ OptionalProperty1Tag = "OptionalProperty1Value" }
   Oracle Example: -extraProps @{ Database = "VmanDB" }
.PARAMETER InputParameters
   HashTable of values containing the parameters required to make the API call
.EXAMPLE
   $CreateAccountJSON = Add-VPASAccount -platformID {PLATFORMID VALUE} -safeName {SAFENAME VALUE} -address {ADDRESS VALUE} -username {USERNAME VALUE}
.EXAMPLE
   $CreateAccountJSON = Add-VPASAccount -platformID {PLATFORMID VALUE} -safeName {SAFENAME VALUE} -address {ADDRESS VALUE} -username {USERNAME VALUE} -extraProps @{Database = "DatabaseName"; Port = "1234"}
.EXAMPLE
   $InputParameters = @{
        platformID = "TargetPlatform"
        safeName = "TargetSafeName"
        accessRestrictedToRemoteMachines = "TRUE"|"FALSE"
        automaticManagementEnabled = "TRUE"|"FALSE"
        manualManagementReason = "Reason to disable rotation"
        extraProps = @{
            ExtraProperty1 = "ExtraProperty1Value"
            ExtraProperty2 = "ExtraProperty2Value"
        }
        secretType = "Password"|"Key"
        address = "AddressHere"
        username = "UsernameHere"
        secret = "Cyberark1"
   }
   $CreateAccountJSON = Add-VPASAccount -InputParameters $InputParameters
.OUTPUTS
   If successful:
   {
        "categoryModificationTime": 1723780054,
        "platformId": "WinDomain",
        "safeName": "TestSafe",
        "id": "121_5",
        "name": "Operating System-WinDomain-vman.com-testdomainuser02",
        "address": "vman.com",
        "userName": "testdomainuser02",
        "secretType": "password",
        "secretManagement": {
                                 "automaticManagementEnabled": true,
                                 "lastModifiedTime": 1723780054
                             },
        "createdTime": 1723780054
   }
   ---
   $false if failed
#>

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

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter platform of new account (for example: WinServerLocal)")]
        [String]$platformID,

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

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [ValidateSet('TRUE','FALSE')]
        [String]$accessRestrictedToRemoteMachines,

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

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [ValidateSet('TRUE','FALSE')]
        [String]$automaticManagementEnabled,

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

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [hashtable]$extraProps,

        [Parameter(Mandatory=$false,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true)]
        [ValidateSet('Password','Key')]
        [String]$secretType,

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

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter Address of new account (for example: Server1.vman.com)")]
        [String]$address,

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter Username of new account (for example: LocalAdmin)")]
        [String]$username,

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

        [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 = @("platformID","safeName","accessRestrictedToRemoteMachines","remoteMachines","automaticManagementEnabled","manualManagementReason","extraProps","secretType","name","address","username","secret")
                        MandatoryKeys = @("platformID","safeName","address","username")
                    }
                }
                $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 ACCOUNT"
            Write-VPASOutput -str $_ -type E
            return $false
        }

        $pplatformID = $platformID
        $psafeName = $safeName
        $pname = $name
        $paddress = $address
        $puserName = $username
        $psecretType = $secretType
        $psecret = $secret
        $pautomaticManagementEnabled = $automaticManagementEnabled
        $pmanualManagementReason = $manualManagementReason
        $premoteMachines = $remoteMachines
        $paccessRestrictedToRemoteMachines = $accessRestrictedToRemoteMachines
        $pextraProps = $extraProps


        #PLATFORMID SECTION
        if([String]::IsNullOrEmpty($pplatformID)){
            Write-Verbose "PLATFORMID CAN NOT BE NULL"
            Write-VPASOutput -str "PLATFORMID CAN NOT BE NULL" -type E
            return $false
        }

        #SAFENAME SECTION
        if([String]::IsNullOrEmpty($psafeName)){
            Write-Verbose "SAFENAME CAN NOT BE NULL"
            Write-VPASOutput -str "SAFENAME CAN NOT BE NULL" -type E
            return $false
        }

        #RESTRICTED REMOTE MACHINES SECTION
        if(![String]::IsNullOrEmpty($paccessRestrictedToRemoteMachines)){
            $paccessRestrictedToRemoteMachines = $paccessRestrictedToRemoteMachines.ToLower()
            if($paccessRestrictedToRemoteMachines -eq "true" -or $paccessRestrictedToRemoteMachines -eq "false"){
                $remoteMachinesAccess = @{"remoteMachines"="$premoteMachines";"accessRestrictedToRemoteMachines"="$paccessRestrictedToRemoteMachines"}
            }
            else{
                Write-Verbose "IF accessRestrictedToRemoteMachines PARAMETERS IS PASSED, IT MUST BE EITHER TRUE OR FALSE"
                Write-VPASOutput -str "IF accessRestrictedToRemoteMachines PARAMETER IS PASSED, IT MUST BE EITHER TRUE OR FALSE" -type E
                return $false
            }
        }
        elseif($paccessRestrictedToRemoteMachines -eq ""){
            $remoteMachinesAccess = ""
        }

        #AUTOMATIC MANAGEMENT SECTION
        if(![String]::IsNullOrEmpty($pautomaticManagementEnabled)){
            $pautomaticManagementEnabled = $pautomaticManagementEnabled.ToLower()
            if($pautomaticManagementEnabled -eq "true" -or $pautomaticManagementEnabled -eq "false"){
                $secretManagement = @{"automaticManagementEnabled"="$pautomaticManagementEnabled";"manualManagementReason"="$pmanualManagementReason"}
            }
            else{
                Write-Verbose "IF AutomaticManagementEnabled PARAMETERS IS PASSED, IT MUST BE EITHER TRUE OR FALSE"
                Write-VPASOutput -str "IF AutomaticManagementEnabled PARAMETER IS PASSED, IT MUST BE EITHER TRUE OR FALSE" -type E
                return $false
            }
        }

        #EXTRA PROPS SECTION
        if($pextraProps){
            Write-Verbose "HANDLING EXTRA PROPERTIES BEING PASSED"
            $platformAccountProperties = @{}
            $AllKeys = $pextraProps.Keys
            foreach($key in $AllKeys){
                $val = $pextraProps."$key"
                $platformAccountProperties += @{
                    $key = $val
                }
            }
        }

        #SECRET TYPE SECTION
        if(![String]::IsNullOrEmpty($psecretType)){
            $psecretType = $psecretType.ToLower()
            if($psecretType -eq "password" -or $psecretType -eq "key"){
                #DO NOTHING
            }
            else{
                Write-Verbose "SECRETTYPE CAN ONLY BE OF TYPE password OR OF TYPE key"
                Write-VPASOutput -str "SECRETTYPE CAN ONLY BE OF TYPE password OR OF TYPE key" -type E
                return $false
            }
        }
        else{
            $secretType = "password"
        }

        try{
            Write-Verbose "CONSTRUCTING PARAMETERS FOR API CALL"
            $params = @{
                platformId = $platformID;
                safeName = $safeName;
                address = $address;
                userName = $userName;
                secretType = $secretType;
                secret = $secret;
                platformAccountProperties = $platformAccountProperties;
                secretManagement = $secretManagement;
                remoteMachinesAccess = $remoteMachinesAccess;
            }

            if(![String]::IsNullOrEmpty($pname)){
                $params += @{name = $name}
            }

            $log = Write-VPASTextRecorder -inputval $params -token $token -LogType PARAMS
            $params = $params | ConvertTo-Json
            Write-Verbose "MAKING API CALL TO CYBERARK"

            if($NoSSL){
                Write-Verbose "NO SSL ENABLED, USING HTTP INSTEAD OF HTTPS"
                $uri = "http://$PVWA/PasswordVault/api/Accounts"
            }
            else{
                Write-Verbose "SSL ENABLED BY DEFAULT, USING HTTPS"
                $uri = "https://$PVWA/PasswordVault/api/Accounts"
            }

            $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 "UNABLE TO ADD ACCOUNT INTO CYBERARK"
            Write-VPASOutput -str $_ -type E
            return $false
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}