obtener_estado_de_plan_de_mantenimiento_de_sql_server

Esto sube los resultados a la API

$hostname = $(hostname)
 
# Parámetros
$server = $hostname
 
# Fecha actual y rango de los últimos 1 días
$today = (Get-Date).ToString("yyyyMMdd")
$sevenDaysAgo = (Get-Date).AddDays(-1).ToString("yyyyMMdd")
 
# Consulta SQL
$query = @"
SELECT
    j.name AS JobName,
    j.enabled AS IsEnabled,
    h.run_date AS RunDate,
    h.run_time AS RunTime,
    h.run_status AS RunStatus,
    h.message AS Message
FROM
    msdb.dbo.sysjobs j
LEFT JOIN
    msdb.dbo.sysjobhistory h
ON
    j.job_id = h.job_id
WHERE
    h.run_date BETWEEN $sevenDaysAgo AND $today
ORDER BY
    h.run_date DESC, h.run_time DESC
"@
 
# Ejecutar la consulta SQL y capturar resultados
$sqlResults = Invoke-Sqlcmd -ServerInstance $server -Query $query
 
# Crear una lista para almacenar los resultados formateados
$jsonPayload = @()
 
# Convertir cada fila de los resultados a un objeto JSON compatible con el backend
foreach ($row in $sqlResults) {
    # Formatear RunDate y RunTime como fecha completa
    $runDateTime = "{0:0000}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00}" -f (
        [int]($row.RunDate / 10000),
        [int](($row.RunDate % 10000) / 100),
        [int]($row.RunDate % 100),
        [int]($row.RunTime / 10000),
        [int](($row.RunTime % 10000) / 100),
        [int]($row.RunTime % 100)
    )
 
    # Convert RunStatus to text
    $statusText = switch ($row.RunStatus) {
        0 { "Fail" }
        1 { "Success" }
        2 { "Retry" }
        3 { "Canceled" }
        4 { "In Progress" }
        Default { "Unknown" }
    }
 
    # Crear un objeto con los campos requeridos
    $entry = @{
        hostname      = $hostname
        vmname        = $row.JobName
        creationtime  = $runDateTime
        type          = "Backup"
        result        = $statusText
        detail        = $row.Message
    }
 
    # Agregar el objeto a la lista
    $jsonPayload += $entry
}
 
 
# Wrap the payload as a dictionary
$jsonPayloadDict = @{
    hostname = $hostname
    restorePoints = $jsonPayload
}
 
# Convertir la lista a JSON
$jsonOutput = $jsonPayloadDict | ConvertTo-Json -Depth 10
 
# Lógica para enviar el JSON al backend
$uri = "https://api.facundoitest.space/upload"
#$uri = "https://whoami.facundoitest.space"
$headers = @{
    "Content-Type" = "application/json"
    "Authorization" = "bXktbG********************0cmluZw=="
}
 
# Encode the JSON string as UTF-8 bytes, and then explicitly as a UTF-8 string
$utf8JsonBytes = [System.Text.Encoding]::UTF8.GetBytes($jsonOutput)
$utf8JsonString = [System.Text.Encoding]::UTF8.GetString($utf8JsonBytes)
 
# Send the UTF-8 encoded JSON data to your API
Invoke-RestMethod -Uri $uri -Method Post -Body ([System.Text.Encoding]::UTF8.GetBytes($utf8JsonString)) -Headers $headers -ContentType 'application/json; charset=utf-8'
obtener_estado_de_plan_de_mantenimiento_de_sql_server.txt · Last modified: 2024/11/22 16:27 by oso