public/Add-VPASAccount.ps1

<#
.Synopsis
   CREATE ACCOUNT
   CREATED BY: Vadim Melamed, EMAIL: vmelamed5@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO CREATE A NEW ACCOUNT IN CYBERARK
.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 an array following this pattern: @('OptionalProperty1Tag','OptionalProperty1Value','OptionalProperty2Tag','OptionalProperty2Value')
   Oracle Example: -extraProps @('DatabaseName','VmanDB','Port','1521')
.EXAMPLE
   $CreateAccountJSON = Add-VPASAccount -platformID {PLATFORMID VALUE} -safeName {SAFENAME VALUE} -address {ADDRESS VALUE} -username {USERNAME VALUE}
.OUTPUTS
   JSON Object (Account) if successful
   $false if failed
#>

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

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

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

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

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=3)]
        [String]$remoteMachines,

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

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=5)]
        [String]$manualManagementReason,

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=6)]
        [String]$extraProps,

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

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=8)]
        [String]$name,

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

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

        [Parameter(Mandatory=$false,ValueFromPipelineByPropertyName=$true,Position=11)]
        [String]$secret,

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

    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 PLATFORMID VALUE"
        Write-Verbose "SUCCESSFULLY PARSED SAFENAME VALUE"
        Write-Verbose "SUCCESSFULLY PARSED ADDRESS VALUE"
        Write-Verbose "SUCCESSFULLY PARSED USERNAME VALUE"

        $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(![String]::IsNullOrEmpty($pextraProps)){
            Write-Verbose "HANDLING EXTRA PROPERTIES BEING PASSED"
            $platformAccountProperties = @{}
            $splitstr = $extraProps -split ","
            for($i=0;$i -lt $splitstr.length; $i++){
                $platformAccountProperties.Add($splitstr[$i],$splitstr[$i+1])
                $i = $i + 1
            }
        }

        #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
    }
}