Untitled

 avatar
unknown
plain_text
a month ago
2.6 kB
4
Indexable
param(
    [string]$ServiceNowInstance,
    [string]$User,
    [string]$Password,
    [string]$ClassName,
    [string]$CIID,
    [string]$AppVersion
)

Write-Host "Starting script..."

# Encode the credentials
$AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${User}:${Password}"))

function Get-ApplicationVersionValue {
    param(
        [string]$ServiceNowInstance,
        [string]$CIID,
        [string]$ClassName
    )

    $ApiUrl = "$ServiceNowInstance/api/now/cmdb/instance/$ClassName/$CIID"

    $response = Invoke-RestMethod -Uri $ApiUrl -Method Get -Headers @{
        "Authorization" = "Basic $AuthInfo"
    }

    $versionNumber = $response.result.attributes.version

    Write-Host $versionNumber

    return $versionNumber
}

function Update-AttributeValue {
    param(
        [string]$ServiceNowInstance,
        [string]$CIID,
        [string]$ClassName,
        [string]$Value
    )
    $ApiUrl = "$ServiceNowInstance/api/now/cmdb/instance/$className/$CIID"

    Write-Host "API URL: $ApiUrl"

    $Payload = @{
        attributes = @{
            version = $Value
        }
        source = "ServiceNow"
    } | ConvertTo-Json -Depth 10

    Invoke-RestMethod -Uri $ApiUrl -Method Patch -Headers @{
        "Authorization" = "Basic $AuthInfo"
        "Content-Type"  = "application/json"
    } -Body $Payload -ErrorAction Stop
}

try {
    # Get the current version  
    $currentVersion = Get-ApplicationVersionValue -ServiceNowInstance $ServiceNowInstance -CIID $ciID -ClassName $className

    # Check if currentVersion is null or empty  
    if (-not $currentVersion) {
        Update-AttributeValue -ServiceNowInstance $ServiceNowInstance -CIID $CIID -ClassName $className -Value $AppVersion
        Write-Host "Successfully updated 'version' attribute with value: $AppVersion"
        return
    }

    $currentVersionObj = [version]$currentVersion
    $AppVersionObj = [version]$AppVersion

    # Check if the AppVersion is older or equal than the current version  
    if ($AppVersionObj -le $currentVersionObj) {
        Write-Warning "The version being deployed ($AppVersion) is older or equal than the current version ($currentVersion)."
        exit 1
    }

    Update-AttributeValue -ServiceNowInstance $ServiceNowInstance -CIID $CIID -ClassName $className -Value $AppVersion
    Write-Host "Successfully updated 'version' attribute with value: $AppVersion"
} catch {
    Write-Error "Error: $($_.Exception.Message)"
}

 
Editor is loading...
Leave a Comment