(+351) 21 24 10006  ·  info@bconcepts.pt
Carnaxide, Lisboa
PowerShell

PowerShell y APIs REST: consumir y automatizar servicios externos

João Barros 24 de July de 2025 1 min de lectura

PowerShell es un cliente HTTP de primera clase con Invoke-RestMethod e Invoke-WebRequest. Combinado con su capacidad nativa de manipular JSON y XML, es ideal para integrar APIs externas en automatizaciones sin código adicional.

Autenticación OAuth2 (Client Credentials)

# Obtener un token de acceso (Azure AD / Entra ID)
$body = @{
    grant_type    = "client_credentials"
    client_id     = $env:APP_CLIENT_ID
    client_secret = $env:APP_CLIENT_SECRET
    scope         = "https://graph.microsoft.com/.default"
}

$tokenResponse = Invoke-RestMethod `
    -Method POST `
    -Uri "https://login.microsoftonline.com/$env:TENANT_ID/oauth2/v2.0/token" `
    -ContentType "application/x-www-form-urlencoded" `
    -Body $body

$token = $tokenResponse.access_token

GET con headers de autenticación

# Headers reutilizables
$headers = @{
    Authorization  = "Bearer $token"
    "Content-Type" = "application/json"
}

# Llamada GET
$users = Invoke-RestMethod `
    -Method GET `
    -Uri "https://graph.microsoft.com/v1.0/users" `
    -Headers $headers

$users.value | Select-Object displayName, mail | Format-Table

Paginación automática

# Recopilar todas las páginas de resultados
$url     = "https://graph.microsoft.com/v1.0/users?$top=100"
$results = @()

do {
    $response = Invoke-RestMethod -Uri $url -Headers $headers -Method GET
    $results += $response.value
    $url = $response."@odata.nextLink"
} while ($url)

Write-Output "Total usuarios: $($results.Count)"

POST — crear recursos vía API

# Crear un grupo vía la Graph API
$body = @{
    displayName     = "Equipo Analytics"
    mailEnabled     = $false
    securityEnabled = $true
    mailNickname    = "equipo-analytics"
} | ConvertTo-Json

Invoke-RestMethod `
    -Method POST `
    -Uri "https://graph.microsoft.com/v1.0/groups" `
    -Headers $headers `
    -Body $body

Conclusión

PowerShell + Invoke-RestMethod cubre el 95% de las integraciones con APIs modernas. Para automatizaciones empresariales que combinan M365, Azure y sistemas externos sin SDK dedicado, es la herramienta más rápida de implementar y más fácil de mantener.

Compartir: