pc-inventory/agent.ps1
2026-05-18 15:36:47 +02:00

67 lines
2.5 KiB
PowerShell

param(
[string]$ServerUrl = "http://192.168.178.24:8080"
)
$ComputerName = $env:COMPUTERNAME
$User = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$IPAddress = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceAlias "Ethernet*", "Wi-Fi*" | Select-Object -First 1).IPAddress
$MacAddress = (Get-NetAdapter | Where-Object { $_.Status -eq 'Up' } | Select-Object -First 1).MacAddress
$LastSeen = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
# Get installed software from registry (32 and 64 bit)
$Software = @()
$RegistryPaths = @(
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*",
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*",
"HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
)
foreach ($Path in $RegistryPaths) {
Get-ItemProperty $Path -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -ne $null } | ForEach-Object {
$Software += @{
Name = $_.DisplayName
Version = $_.DisplayVersion
}
}
}
# Unique list and sort
$Software = $Software | Sort-Object Name -Unique
# Force Software to be an array even if it has only one element (for PS 5.1 compatibility)
if ($null -eq $Software) {
$Software = @()
}
$Inventory = @{
ComputerName = $ComputerName
User = $User
IPAddress = $IPAddress
MacAddress = $MacAddress
LastSeen = $LastSeen
Software = @($Software) # Ensure it's wrapped in an array
}
# In PowerShell 5.1, ConvertTo-Json still flattens single-item arrays in some cases.
# We can use a trick to ensure it stays an array or use PS7's -AsArray if available.
$Json = $Inventory | ConvertTo-Json -Depth 10
if ($Software.Count -eq 1) {
# Manual fix for PS 5.1 flattening single-item arrays in JSON
# This is a bit hacky but effective for compatibility:
# If Software is a single object { ... }, replace it with [ { ... } ]
# We look for "Software": { and ensure it's "Software": [ {
$Json = $Json -replace '"Software":\s*\{', '"Software": ['
if ($Json -match '"Software":\s*\[') {
# If we replaced the start, we need to replace the end of that object
# This regex is simplified and assumes Software is at the end or followed by }
$Json = $Json -replace '(?ms)("Software":\s*\[.*?)\}(\s*\})', '$1}]$2'
}
}
try {
Invoke-RestMethod -Uri "$ServerUrl/inventory" -Method Post -Body $Json -ContentType "application/json"
Write-Host "Inventory sent successfully to $ServerUrl"
} catch {
Write-Error "Failed to send inventory: $_"
}