public/Update-VPASAccountFields.ps1

<#
.Synopsis
   UPDATE ACCOUNT FIELDS
   CREATED BY: Vadim Melamed, EMAIL: vpasmodule@gmail.com
.DESCRIPTION
   USE THIS FUNCTION TO UPDATE AN ACCOUNT FIELD FOR AN ACCOUNT IN CYBERARK
.LINK
   https://vpasmodule.com/commands/Update-VPASAccountFields
.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 safe
   Safe name that will be used to query for the target account if no AcctID is passed
.PARAMETER username
   Username that will be used to query for the target account if no AcctID is passed
.PARAMETER platform
   PlatformID that will be used to query for the target account if no AcctID is passed
.PARAMETER address
   Address that will be used to query for the target account if no AcctID is passed
.PARAMETER AcctID
   Unique ID that maps to a single account, passing this variable will skip any query functions
.PARAMETER action
   Which action will be taken on the updated fields
   Possible values: Add, Remove, Replace
.PARAMETER field
   Define which field will be updated
   Possible values: Name, Address, PlatformID, Username, Status, StatusReason, RemoteMachines, AccessRestrictedToRemoteMachines, LogonDomain, AutomaticManagementEnabled, ManualManagementReason
.PARAMETER fieldval
   Target value that will be used to update the target field
.PARAMETER CustomField
   Target property tag that will be updated
.PARAMETER InputParameters
   HashTable of values containing the parameters required to make the API call
.EXAMPLE
   $UpdateAccountFieldsJSON = Update-VPASAccountFields -safe {SAFE VALUE} -username {USERNAME VALUE} -action {ACTION VALUE} -field {FIELD VALUE} -fieldval {FIELDVAL VALUE}
.EXAMPLE
   $InputParameters = @{
        safe = "TargetSafeName"
        platform = "TargetPlatformID"
        username = "TargetUsername"
        address = "TargetAddress"
        action = "Add"|"Remove"|"Replace"
        field = "Name"|"Address"|"PlatformID"|"Username"|"Status"|"StatusReason"|"RemoteMachines"|"AccessRestrictedToRemoteMachines"|"LogonDomain"|"CustomField"|"AutomaticManagementEnabled"|"ManualManagementReason"
        fieldval = "UpdatedFieldValue"
        CustomField = "CustomFileCategory"
   }
   $UpdateAccountFieldsJSON = Update-VPASAccountFields -InputParameters $InputParameters
.EXAMPLE
   $InputParameters = @{
        AcctID = "22_312"
        action = "Add"|"Remove"|"Replace"
        field = "Name"|"Address"|"PlatformID"|"Username"|"Status"|"StatusReason"|"RemoteMachines"|"AccessRestrictedToRemoteMachines"|"LogonDomain"|"CustomField"|"AutomaticManagementEnabled"|"ManualManagementReason"
        fieldval = "UpdatedFieldValue"
        CustomField = "CustomFileCategory"
   }
   $UpdateAccountFieldsJSON = Update-VPASAccountFields -InputParameters $InputParameters
.OUTPUTS
   If successful:
   {
        "categoryModificationTime": 1723869049,
        "platformId": "WinDomain",
        "safeName": "TestSafe",
        "id": "121_5",
        "name": "Operating System-WinDomain-vman.com-testdomainuser02",
        "address": "NewAddress.vman.com",
        "userName": "testdomainuser02",
        "secretType": "password",
        "secretManagement": {
                                 "automaticManagementEnabled": true,
                                 "lastModifiedTime": 1723780054
                             },
        "createdTime": 1723780054
   }
   ---
   $false if failed
#>

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

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

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

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

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

        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Unique AccountID of the target account (for example: 22_123)")]
        [String]$AcctID,

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter update type (Add, Remove, Replace)")]
        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter update type (Add, Remove, Replace)")]
        [ValidateSet('Add','Remove','Replace')]
        [String]$action,

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter target field to update (Name, Address, PlatformID, Username. Status, StatusReason, AutomaticManagementEnabled, ManualManagementReason, RemoteMachines, AccessRestrictedToRemoteMachines, LogonDomain, CustomField)")]
        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter target field to update (Name, Address, PlatformID, Username. Status, StatusReason, AutomaticManagementEnabled, ManualManagementReason, RemoteMachines, AccessRestrictedToRemoteMachines, LogonDomain, CustomField)")]
        [ValidateSet('Name','Address','PlatformID','Username','Status','StatusReason','AutomaticManagementEnabled','ManualManagementReason','RemoteMachines','AccessRestrictedToRemoteMachines','LogonDomain','CustomField')]
        [String]$field,

        [Parameter(Mandatory=$true,ParameterSetName='Set1',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter updated value for target field")]
        [Parameter(Mandatory=$true,ParameterSetName='Set2',ValueFromPipelineByPropertyName=$true,HelpMessage="Enter updated value for target field")]
        [String]$fieldval,

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

        [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","platform","username","address","action","field","fieldval","CustomField")
                        MandatoryKeys = @("action","field","fieldval")
                    }
                    set2 = @{
                        AcceptableKeys = @("AcctID","action","field","fieldval","CustomField")
                        MandatoryKeys = @("AcctID","action","field","fieldval")
                    }
                }
                $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 RETRIEVE ACCOUNT"
            Write-VPASOutput -str $_ -type E
            return $false
        }


        Write-Verbose "PARSING TARGET FIELD"
        $fieldlower = $field.ToLower()
        if($fieldlower -eq "name"){
            $triggeractionfield = 1
            Write-Verbose "NAME FIELD SELECTED"
        }
        elseif($fieldlower -eq "address"){
            $triggeractionfield = 2
            Write-Verbose "ADDRESS FIELD SELECTED"
        }
        elseif($fieldlower -eq "platformid"){
            $triggeractionfield = 3
            Write-Verbose "PLATFORMID FIELD SELECTED"
        }
        elseif($fieldlower -eq "username"){
            $triggeractionfield = 4
            Write-Verbose "USERNAME FIELD SELECTED"
        }
        elseif($fieldlower -eq "status"){
            Write-Verbose "STATUS FIELD SELECTED"
            $triggeractionfield = 5
            $fieldvaltemp = $fieldval.ToLower()
            if($fieldvaltemp -eq "true" -or $fieldvaltemp -eq "false"){
                Write-Verbose "ACCEPTABLE VALUE FOR STATUS FIELD"
            }
            else{
                $log = Write-VPASTextRecorder -inputval "FIELDVAL CAN ONLY BE true OR false FOR EDITING status FIELD" -token $token -LogType MISC
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                Write-Verbose "FIELDVAL CAN ONLY BE true OR false FOR EDITING status FIELD"
                Write-VPASOutput -str "FIELDVAL CAN ONLY BE true OR false FOR EDITING status FIELD" -type E
                return $false
            }
        }
        elseif($fieldlower -eq "automaticmanagementenabled"){
            Write-Verbose "AUTOMATIC MANAGEMENT ENABLED FIELD SELECTED"
            $triggeractionfield = 5
            $fieldvaltemp = $fieldval.ToLower()
            if($fieldvaltemp -eq "true" -or $fieldvaltemp -eq "false"){
                Write-Verbose "ACCEPTABLE VALUE FOR AUTOMATIC MANAGEMENT ENABLED FIELD"
            }
            else{
                $log = Write-VPASTextRecorder -inputval "FIELDVAL CAN ONLY BE true OR false FOR EDITING automaticmanagementenabled FIELD" -token $token -LogType MISC
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                Write-Verbose "FIELDVAL CAN ONLY BE true OR false FOR EDITING automaticmanagementenabled FIELD"
                Write-VPASOutput -str "FIELDVAL CAN ONLY BE true OR false FOR EDITING automaticmanagementenabled FIELD" -type E
                return $false
            }
        }
        elseif($fieldlower -eq "statusreason"){
            $triggeractionfield = 6
            Write-Verbose "STATUS REASON FIELD SELECTED"
        }
        elseif($fieldlower -eq "manualmanagementreason"){
            $triggeractionfield = 6
            Write-Verbose "MANUAL MANAGEMENT REASON FIELD SELECTED"
        }
        elseif($fieldlower -eq "remotemachines"){
            $triggeractionfield = 7
            Write-Verbose "REMOTE MACHINES FIELD SELECTED"
        }
        elseif($fieldlower -eq "accessrestrictedtoremotemachines"){
            Write-Verbose "ACCESS RESTRICTED TO REMOTE MACHINES FIELD SELECTED"
            $triggeractionfield = 8
            $fieldvaltemp = $fieldval.ToLower()
            if($fieldvaltemp -eq "true" -or $fieldvaltemp -eq "false"){
                Write-Verbose "ACCEPTABLE FIELDVAL VALUE FOR EDITING ACCESS RESTRICTED TO REMOTE MACHINES FIELD"
            }
            else{
                $log = Write-VPASTextRecorder -inputval "FIELDVAL CAN ONLY BE true OR false FOR EDITING AccessRestrictedToRemoteMachines FIELD" -token $token -LogType MISC
                $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
                Write-Verbose "FIELDVAL CAN ONLY BE true OR false FOR EDITING AccessRestrictedToRemoteMachines FIELD"
                Write-VPASOutput -str "FIELDVAL CAN ONLY BE true OR false FOR EDITING AccessRestrictedToRemoteMachines FIELD" -type E
                return $false
            }
        }
        elseif($fieldlower -eq "logondomain"){
            $triggeractionfield = 9
            Write-Verbose "LOGON DOMAIN FIELD SELECTED"
        }
        elseif($fieldlower -eq "customfield"){
            $triggeractionfield = 10
            Write-Verbose "CUSTOM FIELD SELECTED"

            if([String]::IsNullOrEmpty($CustomField)){
                Write-VPASOutput -str "ENTER CUSTOM FIELD TAG: " -type C
                $CustomField = Read-Host
            }
        }

        Write-Verbose "PARSING ACTION VALUE"
        $fieldvalflag = 0
        $actionlower = $action.ToLower()
        if($actionlower -eq "add"){
            Write-Verbose "ADD ACTION SELECTED"
            $triggeraction = 1
            $fieldvalflag = 1
        }
        elseif($actionlower -eq "replace"){
            Write-Verbose "REPLACE ACTION SELECTED"
            $triggeraction = 2
            $fieldvalflag = 1
        }
        elseif($actionlower -eq "remove"){
            Write-Verbose "REMOVE ACTION SELECTED"
            $triggeraction = 3
        }


        if([String]::IsNullOrEmpty($AcctID)){
            Write-Verbose "NO ACCTID PROVIDED...INVOKING HELPER FUNCTION TO RETRIEVE UNIQUE ACCOUNT ID BASED ON SPECIFIED PARAMETERS"
            $AcctID = Get-VPASAccountIDHelper -token $token -safe $safe -platform $platform -username $username -address $address
            Write-Verbose "RETURNING ACCOUNT ID"
        }
        else{
            Write-Verbose "ACCTID SUPPLIED, SKIPPING HELPER FUNCTION"
        }


        if($AcctID -eq -1){
            $log = Write-VPASTextRecorder -inputval "COULD NOT FIND UNIQUE ACCOUNT ENTRY, INCLUDE MORE SEARCH PARAMETERS" -token $token -LogType MISC
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "COULD NOT FIND UNIQUE ACCOUNT ENTRY, INCLUDE MORE SEARCH PARAMETERS"
            Write-VPASOutput -str "COULD NOT FIND UNIQUE ACCOUNT ENTRY, INCLUDE MORE SEARCH PARAMETERS" -type E
            return $false
        }
        elseif($AcctID -eq -2){
            $log = Write-VPASTextRecorder -inputval "NO ACCOUNTS FOUND" -token $token -LogType MISC
            $log = Write-VPASTextRecorder -inputval "REST API COMMAND RETURNED: FALSE" -token $token -LogType MISC
            Write-Verbose "NO ACCOUNTS FOUND"
            Write-VPASOutput -str "NO ACCOUNTS FOUND" -type E
            return $false
        }
        else{
            #PATH
            Write-Verbose "PARSING PATH VALUE FOR API CALL"
            if($triggeractionfield -eq 1){ $path = "/name" }
            elseif($triggeractionfield -eq 2){ $path = "/address" }
            elseif($triggeractionfield -eq 3){ $path = "/platformid" }
            elseif($triggeractionfield -eq 4){ $path = "/username" }
            elseif($triggeractionfield -eq 5){ $path = "/secretmanagement/automaticmanagementenabled" }
            elseif($triggeractionfield -eq 6){ $path = "/secretmanagement/manualmanagementreason" }
            elseif($triggeractionfield -eq 7){ $path = "/remotemachinesaccess/remotemachines" }
            elseif($triggeractionfield -eq 8){ $path = "/remotemachinesaccess/accessrestrictedtoremotemachines" }
            elseif($triggeractionfield -eq 9){ $path = "/platformAccountProperties/LogonDomain" }
            elseif($triggeractionfield -eq 10){ $path = "/platformAccountProperties/$CustomField" }
            Write-Verbose "PATH VALUE SET FOR API CALL"

            if($fieldvalflag -eq 1){$value = $fieldval}

            #OP
            try{
                Write-Verbose "MAKING API CALL TO CYBERARK"
                if($triggeraction -eq 1){
                    $op = "add"
                    $params = '[{ "op": "'+$op+'","path": "'+$path+'","value": "'+$value+'"}]'
                    $log = Write-VPASTextRecorder -inputval "PARAMS: $params" -token $token -LogType MISC

                    Write-Verbose "GENERATING PARAMETERS: $params"

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

                    if($sessionval){
                        $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method PATCH -Body $params -ContentType "application/json" -WebSession $sessionval
                    }
                    else{
                        $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method PATCH -Body $params -ContentType "application/json"
                    }
                    $outputlog = $response
                    $log = Write-VPASTextRecorder -inputval $outputlog -token $token -LogType RETURN
                    Write-Verbose "RETURNING JSON OBJECT"
                    return $response
                }
                elseif($triggeraction -eq 2){
                    $op = "replace"
                    $params = '[{ "op": "'+$op+'","path": "'+$path+'","value": "'+$value+'"}]'
                    $log = Write-VPASTextRecorder -inputval "PARAMS: $params" -token $token -LogType MISC

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

                    if($sessionval){
                        $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method PATCH -Body $params -ContentType "application/json" -WebSession $sessionval
                    }
                    else{
                        $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method PATCH -Body $params -ContentType "application/json"
                    }
                    $outputlog = $response
                    $log = Write-VPASTextRecorder -inputval $outputlog -token $token -LogType RETURN
                    Write-Verbose "RETURNING JSON OBJECT"
                    return $response
                }
                elseif($triggeraction -eq 3){
                    $op = "remove"
                    $params = '[{ "op": "'+$op+'","path": "'+$path+'"}]'
                    $log = Write-VPASTextRecorder -inputval "PARAMS: $params" -token $token -LogType MISC

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

                    if($sessionval){
                        $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method PATCH -Body $params -ContentType "application/json" -WebSession $sessionval
                    }
                    else{
                        $response = Invoke-RestMethod -Headers @{"Authorization"=$Header} -Uri $uri -Method PATCH -Body $params -ContentType "application/json"
                    }
                    $outputlog = $response
                    $log = Write-VPASTextRecorder -inputval $outputlog -token $token -LogType RETURN
                    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 UPDATE ACCOUNT FIELD"
                Write-VPASOutput -str $_ -type E
                return $false
            }
        }
    }
    End{
        $log = Write-VPASTextRecorder -inputval $CommandName -token $token -LogType DIVIDER
    }
}