2025-10-08 15:49:22 -03:00
<#
. SYNOPSIS
Recopila información de hardware y software y la envía a la API de Inventario IT .
. DESCRIPTION
Este script utiliza la lógica de recopilación de discos original y probada , adaptada para
funcionar con los nuevos endpoints y la estructura de datos de la API de Inventario IT .
. NOTES
Versión : 2.4
Fecha : 08 / 10 / 2025
- Revertida la lógica de detección de discos para W10 + a la versión original para máxima compatibilidad .
#>
2025-10-08 13:51:27 -03:00
2025-10-08 15:49:22 -03:00
# =================================================================================
2025-10-08 13:51:27 -03:00
# --- CONFIGURACIÓN ---
2025-10-08 15:49:22 -03:00
$apiBaseUrl = " http://equipos.eldia.net/api "
# =================================================================================
2025-10-08 13:51:27 -03:00
2025-10-08 15:49:22 -03:00
# Verificar versión de Windows
2025-10-08 13:51:27 -03:00
$osInfo = Get-WmiObject Win32_OperatingSystem
$isWindows7 = [ version ] $osInfo . Version -lt [ version ] " 6.2 "
if ( $isWindows7 ) {
2025-10-08 15:49:22 -03:00
Write-Host " Ejecutando versión adaptada para Windows 7... "
# Función de conversión JSON básica
function ConvertTo-BasicJson { param ( $InputObject ) ; if ( $InputObject -is [ array ] ) { $json = @ ( ) ; foreach ( $item in $InputObject ) { $json + = ConvertTo-BasicJson -InputObject $item } ; return " [ $( $json -join ',' ) ] " } elseif ( $InputObject -is [ System.Collections.IDictionary ] ) { $props = @ ( ) ; foreach ( $key in $InputObject . Keys ) { $props + = " `" $key `" : $( ConvertTo-BasicJson -InputObject $InputObject [ $key ] ) " } ; return " { $( $props -join ',' ) } " } else { return " `" $( $InputObject . ToString ( ) . Replace ( '"' , '\"' ) ) `" " } }
# Obtener información del sistema
$hostname = $env:COMPUTERNAME ; $username = $env:USERNAME
2025-10-08 13:51:27 -03:00
$activeInterface = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where-Object { $_ . IPEnabled -eq $true -and $_ . DefaultIPGateway -ne $null } | Sort-Object InterfaceIndex | Select-Object -First 1
2025-10-08 15:49:22 -03:00
$ip = if ( $activeInterface ) { $activeInterface . IPAddress [ 0 ] } else { " No IP " } ; $mac = if ( $activeInterface ) { ( $activeInterface . MACAddress ) -replace '-' , ':' } else { " No MAC " }
$cpu = ( Get-WmiObject Win32_Processor ) . Name ; $motherboard = ( Get-WmiObject Win32_BaseBoard ) . Product
$installedRAM = ( Get-WmiObject Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum ) . Sum ; $installedRAMGB = [ math ] :: Round ( $installedRAM / 1 GB , 0 )
$ram_slots = ( Get-WmiObject Win32_PhysicalMemoryArray ) . MemoryDevices
$osName = $osInfo . Caption ; $osArchitecture = $osInfo . OSArchitecture
$memoriasRam = @ ( Get-WmiObject Win32_PhysicalMemory | ForEach-Object { [ PSCustomObject ] @ { partNumber = $_ . PartNumber . Trim ( ) ; fabricante = $_ . Manufacturer . Trim ( ) ; tamano = [ math ] :: Round ( $_ . Capacity / 1 GB , 0 ) ; velocidad = $_ . Speed ; slot = $_ . BankLabel } } )
$jsonDataEquipo = ConvertTo-BasicJson @ { hostname = $hostname ; ip = $ip ; mac = $mac ; cpu = $cpu -join " , " ; motherboard = $motherboard ; ram_installed = $installedRAMGB ; ram_slots = $ram_slots ; os = $osName ; architecture = $osArchitecture }
$jsonDataUsuario = ConvertTo-BasicJson @ { username = $username }
$jsonMemoriasRam = ConvertTo-BasicJson -InputObject $memoriasRam
$memoriasRamMaestra = $memoriasRam | ForEach-Object { $obj = New-Object PSCustomObject ; Add-Member -InputObject $obj -MemberType NoteProperty -Name " partNumber " -Value $_ . partNumber ; Add-Member -InputObject $obj -MemberType NoteProperty -Name " fabricante " -Value $_ . fabricante ; Add-Member -InputObject $obj -MemberType NoteProperty -Name " tamano " -Value $_ . tamano ; Add-Member -InputObject $obj -MemberType NoteProperty -Name " velocidad " -Value $_ . velocidad ; $obj }
$jsonMemoriasRamMaestra = ConvertTo-BasicJson -InputObject $memoriasRamMaestra
# Función de envío WebClient
function Send-Data { param ( $Url , $Body , $Method = " POST " ) ; try { $webClient = New-Object System . Net . WebClient ; $webClient . Headers . Add ( " Content-Type " , " application/json " ) ; return $webClient . UploadString ( $Url , $Method , $Body ) } catch { Write-Host " Error en el envío a $Url : $( $_ . Exception . Message ) " ; return $null } }
2025-10-08 13:51:27 -03:00
} else {
2025-10-08 15:49:22 -03:00
Write-Host " Ejecutando versión estándar para Windows 8/10/11... "
# Obtener información del sistema
$hostname = $env:COMPUTERNAME ; $username = $env:USERNAME
2025-10-08 13:51:27 -03:00
$activeInterface = Get-NetIPConfiguration | Where-Object { $_ . IPv4DefaultGateway -ne $null -and $_ . NetAdapter . Status -eq 'Up' } | Sort-Object InterfaceMetric | Select-Object -First 1
2025-10-08 15:49:22 -03:00
$ip = if ( $activeInterface ) { $activeInterface . IPv4Address . IPAddress } else { " No IP " } ; $mac = if ( $activeInterface ) { ( $activeInterface . NetAdapter . MacAddress ) -replace '-' , ':' } else { " No MAC " }
$cpu = ( Get-CimInstance Win32_Processor ) . Name ; $motherboard = ( Get-CimInstance Win32_BaseBoard ) . Product
$installedRAM = ( Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property Capacity -Sum ) . Sum ; $installedRAMGB = [ math ] :: Round ( $installedRAM / 1 GB , 0 )
$os = Get-CimInstance Win32_OperatingSystem ; $osName = $os . Caption ; $osArchitecture = $os . OSArchitecture
$memoriasRam = @ ( Get-CimInstance Win32_PhysicalMemory | ForEach-Object { [ PSCustomObject ] @ { partNumber = $_ . PartNumber . Trim ( ) ; fabricante = $_ . Manufacturer . Trim ( ) ; tamano = [ math ] :: Round ( $_ . Capacity / 1 GB , 0 ) ; velocidad = $_ . Speed ; slot = $_ . DeviceLocator } } )
$jsonDataEquipo = @ { hostname = $hostname ; ip = $ip ; mac = $mac ; cpu = $cpu ; motherboard = $motherboard ; ram_installed = $installedRAMGB ; ram_slots = ( Get-CimInstance -ClassName Win32_PhysicalMemoryArray | Measure-Object -Property MemoryDevices -Sum ) . Sum ; os = $osName ; architecture = $osArchitecture } | ConvertTo-Json -Depth 10 -Compress
$jsonDataUsuario = @ { username = $username } | ConvertTo-Json -Compress
$jsonMemoriasRam = $memoriasRam | ConvertTo-Json -Depth 10 -Compress
$jsonMemoriasRamMaestra = $memoriasRam | Select-Object -ExcludeProperty slot | ConvertTo-Json -Depth 10 -Compress
2025-10-08 13:51:27 -03:00
}
2025-10-08 15:49:22 -03:00
###################################################################
# CÓDIGO COMÚN PARA OBTENCIÓN DE DISCOS (MÉTODO UNIVERSAL)
###################################################################
Write-Host " Obteniendo información de discos (método compatible)... "
$disks = @ ( Get-WmiObject Win32_DiskDrive | Where-Object { $_ . Size -gt 0 } | ForEach-Object {
$model = $_ . Model
$mediaType = " HDD "
if ( $model -like " *SSD* " -or $model -like " KINGSTON SA400S37* " ) {
$mediaType = " SSD "
}
[ PSCustomObject ] @ { mediatype = $mediaType ; size = [ math ] :: Round ( $_ . Size / 1 GB , 0 ) }
} )
2025-10-08 13:51:27 -03:00
2025-10-08 15:49:22 -03:00
if ( $null -eq $disks -or $disks . Count -eq 0 ) {
Write-Host " [ADVERTENCIA] No se pudo obtener información de los discos. Se enviará una lista vacía. "
$jsonDiscos = " [] "
2025-10-08 13:51:27 -03:00
} else {
2025-10-08 15:49:22 -03:00
# 1. Convertimos la colección a JSON.
$tempJson = $disks | ConvertTo-Json -Depth 10 -Compress
# 2. Verificamos si el texto resultante NO empieza con '[', lo que significa que es un objeto único.
if ( -not $tempJson . StartsWith ( " [ " ) ) {
# 3. Si es un objeto único, lo envolvemos en corchetes para convertirlo en un array de un solo elemento.
$jsonDiscos = " [ $tempJson ] "
} else {
# 4. Si ya es un array, lo usamos tal cual.
$jsonDiscos = $tempJson
}
2025-10-08 13:51:27 -03:00
}
2025-10-08 15:49:22 -03:00
###################################################################
# CÓDIGO COMÚN PARA AMBAS VERSIONES (ENVÍO DE DATOS)
###################################################################
$rutaEquipos = " $apiBaseUrl /equipos/ $hostname " ; $rutaUsuariosAsocia = " $apiBaseUrl /equipos/ $hostname /asociarusuario " ; $rutaUsuarios = " $apiBaseUrl /usuarios "
$rutaDiscos = " $apiBaseUrl /discos " ; $rutaDiscosAsocia = " $apiBaseUrl /equipos/ $hostname /asociardiscos " ; $rutaMemoriasRam = " $apiBaseUrl /MemoriasRam "
$rutaMemoriasRamAsocia = " $apiBaseUrl /equipos/ $hostname /ram "
2025-10-08 13:51:27 -03:00
try {
2025-10-08 15:49:22 -03:00
Write-Host " 1. Enviando/Actualizando datos del equipo... " ; if ( $isWindows7 ) { Send-Data -Url $rutaEquipos -Body $jsonDataEquipo } else { Invoke-RestMethod -Uri $rutaEquipos -Method Post -ContentType " application/json " -Body $jsonDataEquipo } ; Write-Host " -> OK. "
Write-Host " 2. Creando/Actualizando registro de usuario... " ; if ( $isWindows7 ) { Send-Data -Url $rutaUsuarios -Body $jsonDataUsuario } else { Invoke-RestMethod -Uri $rutaUsuarios -Method Post -ContentType " application/json " -Body $jsonDataUsuario } ; Write-Host " -> OK. "
Write-Host " 3. Asociando usuario al equipo... " ; if ( $isWindows7 ) { Send-Data -Url $rutaUsuariosAsocia -Body $jsonDataUsuario } else { Invoke-RestMethod -Uri $rutaUsuariosAsocia -Method Post -ContentType " application/json " -Body $jsonDataUsuario } ; Write-Host " -> OK. "
2025-10-08 13:51:27 -03:00
2025-10-08 15:49:22 -03:00
# --- LLAMADAS A LA API DE DISCOS CON DEPURACIÓN ---
Write-Host " 4. Enviando lista maestra de discos... "
Write-Host " --> DEBUG: Payload para /api/discos: $jsonDiscos " -ForegroundColor Cyan
if ( $isWindows7 ) { Send-Data -Url $rutaDiscos -Body $jsonDiscos } else { Invoke-RestMethod -Uri $rutaDiscos -Method Post -ContentType " application/json " -Body $jsonDiscos } ; Write-Host " -> OK. "
Write-Host " 5. Sincronizando discos con el equipo... "
Write-Host " --> DEBUG: Payload para /api/equipos/.../asociardiscos: $jsonDiscos " -ForegroundColor Cyan
if ( $isWindows7 ) { Send-Data -Url $rutaDiscosAsocia -Body $jsonDiscos } else { Invoke-RestMethod -Uri $rutaDiscosAsocia -Method Post -ContentType " application/json " -Body $jsonDiscos } ; Write-Host " -> OK. "
Write-Host " 6. Enviando lista maestra de Memorias RAM... " ; if ( $isWindows7 ) { Send-Data -Url $rutaMemoriasRam -Body $jsonMemoriasRamMaestra } else { Invoke-RestMethod -Uri $rutaMemoriasRam -Method Post -ContentType " application/json " -Body $jsonMemoriasRamMaestra } ; Write-Host " -> OK. "
Write-Host " 7. Sincronizando Memorias RAM con el equipo... " ; if ( $isWindows7 ) { Send-Data -Url $rutaMemoriasRamAsocia -Body $jsonMemoriasRam } else { Invoke-RestMethod -Uri $rutaMemoriasRamAsocia -Method Post -ContentType " application/json " -Body $jsonMemoriasRam } ; Write-Host " -> OK. "
2025-10-08 13:51:27 -03:00
2025-10-08 15:49:22 -03:00
Write-Host " " ; Write-Host " ======================================== " ; Write-Host " PROCESO FINALIZADO CORRECTAMENTE " ; Write-Host " ======================================== "
2025-10-08 13:51:27 -03:00
} catch {
2025-10-08 15:49:22 -03:00
Write-Host " " ; Write-Host " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! " ; Write-Host " ERROR DURANTE EL ENVÍO DE DATOS " ; Write-Host " !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! "
2025-10-08 13:51:27 -03:00
Write-Host " Detalle del error: $( $_ . Exception . Message ) "
2025-10-08 15:49:22 -03:00
if ( $_ . Exception . Response ) {
try { $stream = $_ . Exception . Response . GetResponseStream ( ) ; $reader = New-Object System . IO . StreamReader ( $stream ) ; $responseBody = $reader . ReadToEnd ( ) ; $reader . Close ( ) ; $stream . Close ( ) ; Write-Host " Respuesta del servidor: $responseBody " } catch { }
}
}