Additional Data Collection
38 min
Tasks
- Task: Implement Collector for SMBIOS UUID
- Description:Collect the system's unique SMBIOS UUID.
- Schema Target:Devices.smbios_uuid
- Verified Method:WMI query SELECT UUID FROM Win32_ComputerSystemProduct.
- Priority:Critical
- Task: Diagnose and Fix USB Controller Collection Error & Implement Data Gathering
- Description:Investigate and fix the USB controller collection error. Collect details (Name, Manufacturer, Status, PNPDeviceID) for USB Host Controllers and Root Hubs.
- Schema Target:DeviceHardware.usb_controllers (JSONB array)
- Verified Method:Debug existing method. Use WMI Win32_USBController, Win32_USBHub and/or PowerShell Get-PnpDevice -Class USB.
- Priority:High (Fixes error)
- Task: Implement Collector for System Chassis Information
- Description:Collect physical chassis information (Manufacturer, Type, Serial Number).
- Schema Target:DeviceHardware.chassis_info (JSONB)
- Verified Method:WMI query SELECT Manufacturer, ChassisTypes, SerialNumber FROM Win32_SystemEnclosure. Map ChassisTypes numbers.
- Priority:High
- Task: Implement Collector for Logical Disk / Volume Information
- Description:Collect details for logical volumes (Mount Point, Label, File System, Capacity, Free Space, Volume GUID/Serial Number, Status).
- Schema Target:DeviceLogicalDisks table
- Verified Method:PowerShell Get-Volume. Map properties.
- Priority:High
- Task: Implement Collector for Physical Disk Drive Information (Basic + SMART)
- Description:Collect key physical disk details (Model, Serial, Interface, Media Type, Capacity, Status) and essential SMART attributes (Temperature, Wear, Errors, PowerOnHours).
- Schema Target:PhysicalDisks table
- Verified Method:PowerShell Get-PhysicalDisk and Get-PhysicalDisk | Get-StorageReliabilityCounter. Requires Storage Module.
- Priority:High
- Task: Implement Collector for Local User Accounts
- Description:Enumerate and collect local user account details (Name, SID, Full Name, Status [Disabled/Locked], Password flags).
- Schema Target:LocalUserAccounts table
- Verified Method:PowerShell Get-LocalUser. is_admin requires Task 8.
- Priority:High
- Task: Implement Collector for Local Groups
- Description:Enumerate and collect local group details (Name, Description, SID).
- Schema Target:LocalGroups table
- Verified Method:PowerShell Get-LocalGroup.
- Priority:High
- Task: Implement Collector for Local Group Memberships (Including Admin Check)
- Description:Enumerate members of local groups. Specifically identify members of the 'Administrators' group to populate LocalUserAccounts.is_admin.
- Schema Target:LocalGroupMemberships table
- Verified Method:PowerShell Get-LocalGroupMember -Group <GroupName> or -SID <GroupSID>. Parse member details. Update LocalUserAccounts.is_admin.
- Priority:High
- Task: Implement Collector for Active/Disconnected User Sessions
- Description:Collect current user session information (Console, RDP) including username, state, and logon time.
- Schema Target:DeviceSessions table
- Verified Method:PowerShell Get-TerminalSession cmdlet.
- Priority:High
- Task: Implement Collector for Installed Printers (Local and Network)
- Description:Enumerate configured printers and their basic status and configuration.
- Schema Target:DevicePrinters table
- Verified Method:WMI query SELECT ... FROM Win32_Printer. Map status/state codes.
- Priority:High
- Task: Implement Collector for Static IP Routes
- Description:Collect non-automatic static IP routes configured on the device.
- Schema Target:DeviceStaticRoutes table
- Verified Method:PowerShell Get-NetRoute | Where-Object {$_.Protocol -eq 'Manual'}. Verify is_persistent mapping.
- Priority:High
- Task: Implement Collector for Detailed Microsoft Defender Configuration (Get-MpPreference)
- Description:Collect the comprehensive configuration settings for Microsoft Defender Antivirus.
- Schema Target:DeviceDefenderConfiguration table
- Verified Method:PowerShell Get-MpPreference. Map properties carefully.
- Priority:High
- Task: Implement Collector for Detailed Audit Policy Settings
- Description:Collect effective advanced audit policy settings (Success/Failure) for all subcategories.
- Schema Target:DetailedAuditPolicySettings table
- Verified Method:Execute auditpol /get /category:* command and parse the output. Map settings strings.
- Priority:High
- Task: Implement Collector for Individual Windows Firewall Rules
- Description:Enumerate and collect details for all configured Windows Firewall rules.
- Schema Target:DeviceFirewallRules table
- Verified Method:PowerShell Get-NetFirewallRule. Handle arrays.
- Priority:High
- Task: Implement Collector for Device Firewall Profile Settings
- Description:Collect the configuration settings for the Domain, Private, and Public Windows Firewall profiles.
- Schema Target:DeviceFirewallProfiles table (profile_name, is_enabled, default_inbound_action, default_outbound_action, etc.)
- Verified Method:PowerShell Get-NetFirewallProfile cmdlet. Iterate through profiles (Domain, Private, Public) and map properties like Enabled, DefaultInboundAction, DefaultOutboundAction.
- Priority:High (Completes Firewall Configuration)
- Task: Implement Collector for Device Drivers
- Description:Collect information about installed device drivers (Name, Provider, Version, Date, Signed Status, PNP ID).
- Schema Target:DeviceDrivers table
- Verified Method:WMI query SELECT Description, ProviderName, DriverVersion, DriverDate, IsSigned, PNPDeviceID FROM Win32_PNPSignedDriver.
- Priority:Medium (Standard inventory item)
- Task: Implement Collector for Device Scheduled Tasks
- Description:Collect information about scheduled tasks configured on the device.
- Schema Target:DeviceScheduledTasks table (task_name [TaskPath+TaskName], status [State], is_enabled [State!=Disabled], last_run_time [LastRunTime], last_run_result [LastTaskResult], next_run_time [NextRunTime], actions [Actions], triggers [Triggers], run_as_user [Principal])
- Verified Method:PowerShell Get-ScheduledTask cmdlet. Map properties. Actions and Triggers are objects that might need serialization (e.g., to JSON) or specific property extraction.
- Priority:Medium (OS configuration visibility)
- Task: Implement Collector for General Hardware Sensor Readings (Temp/Fan/Volt)
- Description:Collect readings from common hardware sensors like CPU/GPU temperature, fan speeds, and voltages.
- Schema Target:DeviceSensorReadings table (sensor_type, sensor_name, reading_value, reading_unit)
- Verified Method:WMI namespace root\WMI classes like MSAcpi_ThermalZoneTemperature or Win32_Fan. Alternatively, investigate root\LibreHardwareMonitor if LibreHardwareMonitor/OpenHardwareMonitor library/service is installed (requires external dependency). PowerShell Get-CimInstance -Namespace root/WMI -ClassName MSAcpi_ThermalZoneTemperature for temps. Fan/Voltage may require the external library route for reliability across hardware.
- Priority:Medium (Hardware health monitoring)
- Notes:Focus on temperature first via WMI. Fan/Voltage is more complex.
- Task: Implement Collector for Detailed Physical RAM Module Information
- Description:Collect details for each installed physical RAM module.
- Schema Target:DeviceHardware.ram_details (JSONB array)
- Verified Method:WMI query SELECT BankLabel, Capacity, FormFactor, MemoryType, Speed, Manufacturer, PartNumber, SerialNumber FROM Win32_PhysicalMemory. Map MemoryType codes.
- Priority:Medium
- Task: Enhance Network Adapter Collector for DHCP Lease, WINS, vSwitch
- Description:Add DHCP lease details, WINS server config, and associated virtual switch name.
- Schema Target:DeviceNetworkAdapters table
- Verified Method:WMI Win32_NetworkAdapterConfiguration. PowerShell Get-VMNetworkAdapter -ManagementOS | Where-Object MacAddress for vSwitch Name.
- Priority:Medium
- Task: Implement Collector for Disk Encryption Status (BitLocker)
- Description:Collect BitLocker status (Encryption Status, Protection Status, Percentage, Lock Status, Key Protector Types).
- Schema Target:DeviceDiskEncryptionStatus table
- Verified Method:PowerShell Get-BitLockerVolume. Map properties. Store key protector types.
- Priority:Medium
- Task: Implement Collector for Battery Status and Health
- Description:Collect battery information, if present.
- Schema Target:DeviceBattery table
- Verified Method:WMI query SELECT ... FROM Win32_Battery. Map codes. Handle absence.
- Priority:Medium
- Task: Implement Collector for Basic OS Upgrade History (Last Upgrade)
- Description:Collect information about the lastOS upgrade performed.
- Schema Target:OsUpgradeHistory table
- Verified Method:Read registry keys under HKLM\SYSTEM\Setup\Source OS. Estimate timestamp.
- Priority:Medium-Low
- Task: Enhance Startup Items Collector for Publisher
- Description:Add publisher information (from digital signature) to startup items.
- Schema Target:DeviceStartupItems table (add publisher)
- Verified Method:PowerShell Get-AuthenticodeSignature on executablePath. Handle errors/unsigned files efficiently.
- Priority:Medium
- Task: Implement Collector for Local User Profile Details (Basic Path/Status/Last Used)
- Description:Collect basic user profile info (Path, Status Flags, Last Used Time).
- Schema Target:LocalUserProfiles table
- Verified Method:WMI query SELECT SID, LocalPath, Status, LastUseTime FROM Win32_UserProfile. Map Status flags.
- Priority:Medium
- Task: Implement Collector for Installed Browsers
- Description:Identify installed web browsers (Edge, Chrome, Firefox, etc.) and their versions/paths/default status.
- Schema Target:DeviceBrowsers table
- Verified Method:Check common registry locations (App Paths, etc.). Get version from file properties or specific browser keys.
- Priority:Medium
- Task: Enhance Endpoint Protection Collector for Engine Version
- Description:Add the specific AV engine version.
- Schema Target:EndpointProtectionStatus table (engine_version)
- Verified Method:PowerShell (Get-MpComputerStatus).AntivirusEngineVersion for Defender. Vendor-specific methods for others.
- Priority:Medium
- Task: Implement Collector for Sound Device Information
- Description:Collect sound device details (Name, Manufacturer).
- Schema Target:DeviceHardware.sound_devices (JSONB array)
- Verified Method:WMI query SELECT Name, Manufacturer FROM Win32_SoundDevice.
- Priority:Medium
- Task: Implement Collector for Network Shares Hosted on Device (Basic Info)
- Description:Enumerate network shares hosted by the local device (Name, Path, Type, Description, Max Users).
- Schema Target:NetworkShares table
- Verified Method:WMI query SELECT Name, Path, Caption, Type, MaximumAllowed FROM Win32_Share. Map numeric Type codes.
- Priority:Medium-Low (Permission collection is separate)
- Task: Implement Collector for Hosted Network Share Permissions
- Description:Collect share-level permissions (ACLs) for network shares hosted on the local device.
- Schema Target:SharePermissions table (network_share_id, account_name, account_sid, access_type, permission)
- Verified Method:For each share from Task 29 (Win32_Share), get the associated Win32_LogicalShareSecuritySetting instance. Call its GetSecurityDescriptor method. Parse the returned SecurityDescriptor. Iterate through the DACL (Discretionary Access Control List). For each ACE (Access Control Entry), extract the Trustee (SID/Name), AceType (Allow/Deny), and AccessMask. Map the AccessMask bits to 'Read', 'Change', or 'FullControl' permissions.
- Priority:Medium-Low (Complex Security Descriptor parsing)
- Notes:Requires careful parsing of Security Descriptors. Focus on share permissions, not deeper NTFS permissions.
- Task: Implement Collector for Mapped Network Drives (Registry Method)
- Description:Attempt to enumerate mapped drives by reading logged-on user registry hives.
- Schema Target:MappedNetworkDrives table
- Verified Method:Iterate user SIDs (Win32_UserProfile). Load hive (reg load). Query HKU\<SID>\Network\<DriveLetter>\RemotePath. Unload hive (reg unload).
- Priority:Low (Complex, potential errors)
- Task: Implement Collector for Windows Activation Status
- Description:Determine Windows activation status and partial product key.
- Schema Target:DeviceSoftware table (linked OS entry: detected_activation_status, detected_license_key)
- Verified Method:WMI query SELECT LicenseStatus, PartialProductKey FROM SoftwareLicensingProduct WHERE ApplicationId = '...'. Map LicenseStatus.
- Priority:Low
- Task: Implement Collector for Browser Policy Configuration (Registry Method)
- Description:Collect policy-enforced browser settings (Edge, Chrome, Firefox) from standard GPO registry locations.
- Schema Target:BrowserConfiguration table
- Verified Method:Query HKLM/HKCU\Software\Policies... for Microsoft\Edge, Google\Chrome, Mozilla\Firefox. Map registry value names.
- Priority:Low
- Task: Implement Collector for Browser Extensions (Multi-Browser, User Context Aware)
- Description:Enumerate installed extensions for Edge, Chrome, Firefox across user profiles.
- Schema Target:BrowserExtensions table
- Verified Method:Complex. Find user profile paths (Task 21), find browser profile paths within them, parse manifests/files/registry keys per browser per user context.
- Priority:Low (High complexity, maintenance required)
- Task: Collect Process Parent PID and Start Time
- Requirement:The agent shall collect the parent process identifier (Parent PID) and the precise start time for each running process inventoried on the device.
- Description:To provide better context for process analysis and troubleshooting, the agent must augment its standard process collection. For every process captured, it needs to determine which process initiated it (the parent) and record the timestamp when the process began execution.
- Data Points Collected:
- parentPid: The numeric Process ID of the parent process.
- startTime: The date and time (UTC, ISO 8601 format) when the process started.
- Source/Method:Utilize standard OS APIs, likely via PowerShell (Get-Process for StartTime) and WMI (Win32_Process for ParentProcessId).
- Target Schema/Output:Data intended for the DeviceProcesses table/JSON structure, specifically populating the parentPid and startTime fields.
- Notes:Handle cases where Parent PID or Start Time might not be available (e.g., system idle process, very short-lived processes, access limitations) by reporting null values.
- Task: Collect Network Connection Snapshot with Process ID Linkage
- Requirement:The agent shall capture a point-in-time snapshot of all current network connections (TCP) and listening endpoints (UDP), associating each with the owning Process ID (PID).
- Description:To understand which applications are responsible for network activity, the agent must enumerate active TCP connections and UDP listeners. Critically, it must identify the specific Process ID associated with each socket/endpoint at the time of the snapshot. This provides more granular detail than simply listing open ports.
- Data Points Collected:
- protocol: TCP or UDP.
- localAddress: Local IP address bound to the socket.
- localPort: Local port number.
- remoteAddress: Remote IP address (for TCP connections).
- remotePort: Remote port number (for TCP connections).
- state: Connection state (e.g., 'Established', 'Listen', 'Time_Wait' for TCP; 'Listening' for UDP).
- processID: The numeric Process ID owning the socket/endpoint.
- Source/Method:Utilize standard OS APIs, likely via PowerShell cmdlets (Get-NetTCPConnection, Get-NetUDPEndpoint).
- Target Schema/Output:Data intended for a table like DeviceNetworkConnectionsSnapshot or similar structure / JSON Array output.
- Notes:This provides a snapshot, not aggregated statistics (bytes/packets) per process over time. It reflects the state at the moment of collection.
- Task: Collect Aggregate Network Interface Performance Statistics
- Requirement:The agent shall collect aggregate network performance counters for each active physical or virtual network interface on the device.
- Description:To monitor overall network throughput and health at the adapter level, the agent must query specific performance counters for each network interface that currently has an 'Up' status. This includes current data transfer rates and cumulative error/discard counts.
- Data Points Collected:
- interface_name: Identifier of the network interface (e.g., description or name).
- bytes_received_per_sec: Current receive rate.
- bytes_sent_per_sec: Current send rate.
- packets_received_per_sec: Current receive packet rate.
- packets_sent_per_sec: Current send packet rate.
- packets_received_errors_total: Cumulative count of inbound packet errors since last reset (usually boot).
- packets_outbound_errors_total: Cumulative count of outbound packet errors since last reset.
- packets_received_discarded_total: Cumulative count of inbound discarded packets since last reset.
- packets_outbound_discarded_total: Cumulative count of outbound discarded packets since last reset.
- Source/Method:Windows Performance Counters (specifically the \Network Interface(*)\... set) via PowerShell (Get-Counter).
- Target Schema/Output:Data intended for the NetworkPortMetrics table (mapping Interface to Port concept) or similar aggregate metrics table / JSON Array output.
- Notes:The collected "per second" values represent the current rateat the time of sampling, not an average or total over the agent's collection interval. Cumulative counters represent totals since the counter was initialized (typically system boot). Calculating interval totals/averages requires server-side processing of multiple data points. This data is per interface, notbroken down per process.
Prompts
Task 1: Collect SMBIOS UUID
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script that collects the system's SMBIOS UUID.
**Instructions:**
1. Use a WMI query to retrieve the UUID.
2. The specific WMI class and property is `Win32_ComputerSystemProduct.UUID`.
3. Handle potential errors where the UUID might be null or inaccessible.
4. Output the collected UUID as a single JSON object.
**Target Schema:** `Devices.smbios_uuid`
**Output JSON Format:**
```json
{
"smbios_uuid": "<Collected UUID or null>"
}
Error Handling:If the UUID cannot be retrieved, the smbios_uuid value in the JSON should be null. The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume the script runs with sufficient privileges (e.g., Administrator or LocalSystem).
Task 2: Collect USB Controller Details
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect details about USB Host Controllers and Root Hubs. Note: A previous attempt resulted in an error (`exit status 1`), so ensure the method is robust.
**Instructions:**
1. Use WMI queries to enumerate USB controllers and hubs.
2. Primarily use `Win32_USBController` and `Win32_USBHub` classes.
3. For each controller/hub found, collect its `Name`, `Manufacturer`, `Status`, and `PNPDeviceID`.
4. Handle potential errors during WMI querying gracefully.
5. Output the collected data as a JSON array of objects, where each object represents one USB controller or hub.
**Target Schema:** `DeviceHardware.usb_controllers` (JSONB array, storing combined controller/hub info)
**Output JSON Format (Array):**
```json
[
{
"name": "<Name>",
"manufacturer": "<Manufacturer>",
"status": "<Status>",
"pnp_device_id": "<PNPDeviceID>"
},
...
]
Error Handling:If WMI queries fail or no controllers/hubs are found, output an empty JSON array []. The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume sufficient privileges.
Task 3: Collect System Chassis Information
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect physical chassis information.
**Instructions:**
1. Use a WMI query to retrieve chassis details from the `Win32_SystemEnclosure` class.
2. Collect the `Manufacturer`, `ChassisTypes`, and `SerialNumber`.
3. Map the numeric value(s) in the `ChassisTypes` array to a descriptive string for the `type` field in the output JSON. Use the *first* value in the array for mapping. Common mappings: 3='Desktop', 6='Mini Tower', 7='Tower', 8='Portable', 9='Laptop', 10='Notebook', 14='Sub Notebook', 30='Blade', 31='Blade Enclosure'. Add others as needed or default to 'Unknown'.
4. Handle potential errors or missing data.
5. Output the collected data as a single JSON object.
**Target Schema:** `DeviceHardware.chassis_info` (JSONB object)
**Output JSON Format:**
```json
{
"manufacturer": "<Manufacturer or null>",
"type": "<Mapped Chassis Type String or 'Unknown'>",
"serial_number": "<SerialNumber or null>"
}
Error Handling:If properties cannot be retrieved, return null for the corresponding JSON field. The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume sufficient privileges.
Task 4: Collect Logical Disk / Volume Information
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect detailed information about logical volumes (disks like C:, D:, etc.).
**Instructions:**
1. Use the `Get-Volume` PowerShell cmdlet.
2. For each volume (excluding hidden/system partitions where possible, e.g., filter by `DriveLetter` not null or check `FileSystemType`), collect the following properties:
* `DriveLetter`
* `FileSystemLabel`
* `UniqueId` (often includes volume GUID)
* `FileSystem`
* `Size`
* `SizeRemaining`
* `HealthStatus`
* `OperationalStatus`
3. Map the collected properties to the specified JSON output format fields.
4. Map the numeric `OperationalStatus` code to a descriptive string (e.g., 0='Unknown', 1='Online', 2='No Media', 3='Failed', 4='Offline', 5='Critical Failure'). Use 'Unknown' if mapping isn't possible. Map `HealthStatus` directly.
5. Output the collected data as a JSON array of objects, where each object represents one logical volume.
**Target Schema:** `DeviceLogicalDisks` table
**Output JSON Format (Array):**
```json
[
{
"mount_point": "<DriveLetter 'C:'>",
"volume_name": "<FileSystemLabel or null>",
"volume_guid": "<UniqueId or null>",
"filesystem_type": "<FileSystem or null>",
"capacity_bytes": <Size as integer>,
"free_space_bytes": <SizeRemaining as integer>,
"status": "<Mapped OperationalStatus string>"
// Add health_status if needed from Get-Volume output
},
...
]
Error Handling:If the cmdlet fails, output an empty JSON array []. Handle missing properties for individual volumes gracefully (use null or default values). The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume sufficient privileges.
Task 5: Collect Physical Disk Drive Information
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect key physical disk drive details, including essential SMART attributes.
**Instructions:**
1. Use the `Get-PhysicalDisk` PowerShell cmdlet to get base disk information.
2. For each physical disk, use `Get-StorageReliabilityCounter` piped from `Get-PhysicalDisk` to retrieve SMART data. Ensure the Storage module is available.
3. Collect the following properties and map them to the JSON fields:
* From `Get-PhysicalDisk`: `FriendlyName` (for manufacturer/model), `Model`, `SerialNumber`, `FirmwareVersion`, `MediaType`, `Size`, `HealthStatus`, `OperationalStatus`, `BusType` (for InterfaceType).
* From `Get-StorageReliabilityCounter`: `Temperature`, `Wear`, `ReadErrorsTotal`, `WriteErrorsTotal`, `PowerOnHours`.
4. Map `BusType` enum to interface type strings (e.g., 'SATA', 'NVMe', 'SAS', 'USB'). Map `MediaType` enum (e.g., 'SSD', 'HDD'). Map `HealthStatus`/`OperationalStatus` to a general `status` string ('Online', 'Failed', 'Warning', 'Unknown').
5. Map the collected SMART counters to the specific schema fields (`smart_temperature_celsius`, `smart_reallocated_sector_count` [use `Wear`? Needs verification/mapping based on counter meaning], `smart_uncorrectable_error_count` [use Read/Write errors?], `power_on_hours`). Record the current timestamp as `smart_last_check_time`.
6. Output the collected data as a JSON array of objects, one per physical disk.
**Target Schema:** `PhysicalDisks` table
**Output JSON Format (Array):**
```json
[
{
"manufacturer": "<Manufacturer from FriendlyName or null>",
"model": "<Model>",
"serial_number": "<SerialNumber>",
"firmware_version": "<FirmwareVersion or null>",
"interface_type": "<Mapped BusType string>",
"media_type": "<Mapped MediaType string>",
"capacity_bytes": <Size as integer>,
"status": "<Mapped Status string>",
"power_on_hours": <PowerOnHours as integer or null>,
"smart_reallocated_sector_count": <Mapped Wear/Reallocated counter or null>,
"smart_pending_sector_count": null, // Often not directly available, set to null
"smart_uncorrectable_error_count": <Mapped Read/Write Error counter or null>,
"smart_temperature_celsius": <Temperature as integer or null>,
"smart_last_check_time": "<Current Timestamp ISO8601 Format>"
},
...
]
Error Handling:If Get-StorageReliabilityCounter fails for a disk (e.g., not supported), populate SMART fields with null. If Get-PhysicalDisk fails, output an empty array []. The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume sufficient privileges and Storage module availability.
Task 6: Collect Local User Accounts
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate and collect details for all local user accounts.
**Instructions:**
1. Use the `Get-LocalUser` PowerShell cmdlet.
2. For each local user account, collect the following properties: `Name`, `FullName`, `Description`, `SID`, `Enabled`, `LockedOut`, `PasswordChangeableUser`, `PasswordExpires`, `PasswordRequired`, `Status`.
3. Map the collected properties to the specified JSON output fields. Note that `is_disabled` is the inverse of the `Enabled` property.
4. Output the data as a JSON array of objects, one per local user. (The `is_admin` field will be populated by Task 8).
**Target Schema:** `LocalUserAccounts` table
**Output JSON Format (Array):**
```json
[
{
"account_name": "<Name>",
"full_name": "<FullName or null>",
"description": "<Description or null>",
"sid": "<SID>",
"is_disabled": <(!Enabled) as boolean>,
"is_locked_out": <LockedOut as boolean or null>,
"is_admin": null, // To be populated later
"password_changeable": <PasswordChangeableUser as boolean or null>,
"password_expires": <PasswordExpires as boolean or null>,
"password_required": <PasswordRequired as boolean or null>,
"status": "<Status string or null>"
},
...
]
Error Handling:If the cmdlet fails, output an empty JSON array []. Handle missing properties for individual users gracefully (use null). The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume sufficient privileges.
Task 7: Collect Local Groups
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate and collect details for all local groups.
**Instructions:**
1. Use the `Get-LocalGroup` PowerShell cmdlet.
2. For each local group, collect the `Name`, `Description`, and `SID` properties.
3. Map the collected properties to the specified JSON output fields.
4. Output the data as a JSON array of objects, one per local group.
**Target Schema:** `LocalGroups` table
**Output JSON Format (Array):**
```json
[
{
"group_name": "<Name>",
"description": "<Description or null>",
"sid": "<SID>"
},
...
]
Error Handling:If the cmdlet fails, output an empty JSON array []. Handle missing properties for individual groups gracefully (use null). The script should not crash.
Provide only the PowerShell script code block for collecting this data.Assume sufficient privileges.
Task 8: Collect Local Group Memberships
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate the members of each local group and determine which local users are administrators. This task depends on having local group SIDs (from Task 7) and local user SIDs (from Task 6).
**Instructions:**
1. First, retrieve all local groups (similar to Task 7) to get their SIDs.
2. For each local group SID, use `Get-LocalGroupMember -SID <GroupSID>` to get its members.
3. For each member, collect their `SID`, `Name`, `PrincipalSource` (e.g., 'Local', 'ActiveDirectory'), and `ObjectClass` ('User', 'Group').
4. Map these details to the `LocalGroupMemberships` JSON structure.
5. While processing members of the group where `Name` is 'Administrators' (or the localized equivalent, or well-known SID 'S-1-5-32-544'), identify members where `ObjectClass` is 'User' and `PrincipalSource` is 'Local'. For these local user SIDs, you will need a mechanism (outside this *specific* script's output, but conceptually related) to update the corresponding `LocalUserAccounts.is_admin` flag to `true`. This script *only* outputs the membership list.
6. Output the group membership data as a JSON array of objects, one per member per group.
**Target Schema:** `LocalGroupMemberships` table. Also informs `LocalUserAccounts.is_admin`.
**Output JSON Format (Array):**
```json
[
{
"group_sid": "<SID of the Group>",
"member_sid": "<SID of the Member>",
"member_name": "<Name of the Member>",
"member_domain": "<PrincipalSource>",
"member_type": "<ObjectClass>"
},
... // Repeat for every member in every group
]
Error Handling:If Get-LocalGroupMember fails for a group, skip that group and continue. If no groups are found, output an empty array []. Handle errors gracefully. The script should not crash.
Provide only the PowerShell script code block for collecting the membership data.Assume sufficient privileges. The update to LocalUserAccounts.is_admin happens conceptually based on this data.
Task 9: Collect Active/Disconnected User Sessions
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect information about current user sessions (Console, RDP, etc.).
**Instructions:**
1. Use the `Get-TerminalSession` PowerShell cmdlet. You might need to use `Import-Module RemoteDesktopServices -ErrorAction SilentlyContinue` first.
2. Filter the results to include relevant sessions (e.g., filter out SessionId 0 or specific states if needed).
3. For each session, collect `UserName`, `SessionName` (like 'Console' or 'RDP-Tcp#0'), `State` (like 'Active', 'Disconnected'), and `LogonTime`.
4. Attempt to determine the `UserDomain` (e.g., query the user object based on `UserName` if it contains a domain, otherwise assume local). This might be complex; output null if difficult.
5. Convert `LogonTime` to UTC ISO8601 format.
6. Map the collected properties to the specified JSON output fields.
7. Output the data as a JSON array of objects, one per session.
**Target Schema:** `DeviceSessions` table
**Output JSON Format (Array):**
```json
[
{
"user_name": "<Username>",
"user_domain": "<DomainName or null>",
"winstation_name": "<SessionName>",
"session_state": "<State string>",
"logon_time_utc": "<LogonTime UTC ISO8601>"
},
...
]
**Error Handling:** If the cmdlet fails or the module isn't available, output an empty JSON array []. If domain lookup fails, output null for user_domain. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 10: Collect Installed Printers (Local and Network)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate configured printers.
**Instructions:**
1. Use a WMI query to retrieve printer details from the `Win32_Printer` class.
2. Collect `Name`, `DriverName`, `PortName`, `Network` (boolean), `Shared` (boolean), `ServerName`, `ShareName`, `Location`, `Default` (boolean), `PrinterStatus`, `PrinterState`, `DetectedErrorState`.
3. Map the numeric `PrinterStatus` and `PrinterState` codes to descriptive strings (e.g., Status: 1='Other', 2='Unknown', 3='Idle', 4='Printing', 5='Warmup'; State: 0='Paused', 1='Error', 2='Pending Deletion', etc.). Use 'Unknown' if mapping unknown. Use `DetectedErrorState` for a more detailed error description string if available.
4. Map the collected properties to the specified JSON output fields.
5. Output the data as a JSON array of objects, one per printer.
**Target Schema:** `DevicePrinters` table
**Output JSON Format (Array):**
```json
[
{
"name": "<Name>",
"device_id_string": null, // Win32_Printer doesn't have DeviceID directly
"driver_name": "<DriverName or null>",
"manufacturer": null, // Not directly available in Win32_Printer
"model": null, // Not directly available in Win32_Printer
"port_name": "<PortName or null>",
"is_network_printer": <Network as boolean>,
"is_shared": <Shared as boolean>,
"server_name": "<ServerName or null>",
"share_name": "<ShareName or null>",
"location": "<Location or null>",
"is_default": <Default as boolean>,
"status": "<Mapped PrinterStatus string>",
"detected_error_state": "<DetectedErrorState string or null>",
"error_description": "<Mapped PrinterState string>"
},
...
]```
**Error Handling:** If the WMI query fails, output an empty JSON array `[]`. Handle missing properties gracefully (use `null`). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 11: Collect Static IP Routes
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect non-automatic static IP routes.
**Instructions:**
1. Use the `Get-NetRoute` PowerShell cmdlet.
2. Filter the results to include only routes where the `Protocol` is 'Manual' (verify this is correct for static routes, might also need 'Local' with extra filtering). Exclude loopback interface routes.
3. For each matching route, collect `DestinationPrefix`, `NextHop`, `RouteMetric`, `InterfaceIndex`.
4. Determine if the route is persistent by checking the `Store` property. Map `Store = 'PersistentStore'` to `is_persistent = true`, otherwise `false`.
5. Map the collected properties to the specified JSON output fields.
6. Output the data as a JSON array of objects, one per static route.
**Target Schema:** `DeviceStaticRoutes` table
**Output JSON Format (Array):**
```json
[
{
"destination_cidr": "<DestinationPrefix>",
"gateway_ip": "<NextHop>",
"metric": <RouteMetric as integer or null>,
"interface_index": <InterfaceIndex as integer or null>,
"interface_name": null, // Requires separate lookup via Get-NetIPConfiguration -InterfaceIndex if needed
"is_persistent": <Mapped Store value as boolean>
},
...
]```
**Error Handling:** If the cmdlet fails or no static routes are found, output an empty JSON array `[]`. Handle errors gracefully. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 12: Collect Detailed Microsoft Defender Configuration (Get-MpPreference)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect detailed Microsoft Defender Antivirus configuration settings.
**Instructions:**
1. Use the `Get-MpPreference` PowerShell cmdlet.
2. Collect a comprehensive set of properties relevant to the `DeviceDefenderConfiguration` schema. Key properties include (but are not limited to): `UILockdown`, `DisableRealtimeMonitoring`, `DisableBehaviorMonitoring`, `DisableIOAVProtection`, `DisableScriptScanning`, `DisableScanOnRealtimeAccess`, `MAPSReporting`, `CloudExtendedTimeout`, `SubmitSamplesConsent`, `PUAProtection`, `ScanOnlyIfIdleEnabled`, `DisableEmailScanning`, `DisableRemovableDriveScanning`, `DisableRestorePoint`, `DisableScanningNetworkFiles`, `DisableArchiveScanning`, `CheckForSignaturesBeforeScan`, `DisableCatchupFullScan`, `DisableCatchupQuickScan`, `ScanAvgCPULoadFactor`, `QuarantinePurgeItemsAfterDelay`, `ScheduledScanDay`, `ScheduledScanTime`, `ScanParameters` (ScheduledScanType), `RandomizeScheduleTaskTimes`, `ThreatIDDefaultAction_Ids`, `AttackSurfaceReductionRules_Ids`, `EnableNetworkProtection`, `EnableControlledFolderAccess`, `ExcludedProcesses`, `ExcludedPaths`, `ExcludedExtensions`, `SignatureUpdateInterval`.
3. Carefully map the collected PowerShell property values to the corresponding `DeviceDefenderConfiguration` schema fields. Pay attention to:
* Boolean inversions (e.g., `DisableRealtimeMonitoring` maps to `is_realtime_monitoring_enabled = !$true`).
* Enum mappings (e.g., `MAPSReporting` codes map to `cloud_block_level`, `PUAProtection` codes map to `is_pua_protection_enabled`, `SubmitSamplesConsent` codes).
* Data type conversions (e.g., `ScheduledScanTime` is TimeSpan, convert to `TIME`).
* Complex types (`ThreatIDDefaultAction_Ids`, `AttackSurfaceReductionRules_Ids` might need to be stored as JSON strings or processed arrays).
4. Output the data as a single JSON object representing the device's Defender configuration.
**Target Schema:** `DeviceDefenderConfiguration` table
**Output JSON Format (Single Object):**
```json
{
"ui_lockdown_enabled": <UILockdown as boolean or null>,
"is_realtime_monitoring_enabled": <(!DisableRealtimeMonitoring) as boolean or null>,
"is_behavior_monitoring_enabled": <(!DisableBehaviorMonitoring) as boolean or null>,
"is_ioav_protection_enabled": <(!DisableIOAVProtection) as boolean or null>,
"is_script_scanning_enabled": <(!DisableScriptScanning) as boolean or null>,
"scan_on_realtime_access_enabled": <(!DisableScanOnRealtimeAccess) as boolean or null>,
"cloud_block_level": "<Mapped MAPSReporting string or null>",
"cloud_extended_timeout": <CloudExtendedTimeout as integer or null>,
"is_cloud_protection_enabled": <(MAPSReporting > 0) as boolean or null>,
"submit_samples_consent": "<Mapped SubmitSamplesConsent string or null>",
"is_pua_protection_enabled": "<Mapped PUAProtection string or null>",
"scan_only_if_idle_enabled": <ScanOnlyIfIdleEnabled as boolean or null>,
"scan_email_enabled": <(!DisableEmailScanning) as boolean or null>,
"scan_removable_drives_enabled": <(!DisableRemovableDriveScanning) as boolean or null>,
"scan_restore_points_enabled": <(!DisableRestorePoint) as boolean or null>,
"scan_network_files_enabled": <(!DisableScanningNetworkFiles) as boolean or null>,
"scan_archives_enabled": <(!DisableArchiveScanning) as boolean or null>,
"check_for_signatures_before_scan": <CheckForSignaturesBeforeScan as boolean or null>,
"catchup_full_scan_enabled": <(!DisableCatchupFullScan) as boolean or null>,
"catchup_quick_scan_enabled": <(!DisableCatchupQuickScan) as boolean or null>,
"avg_cpu_load_factor": <ScanAvgCPULoadFactor as integer or null>,
"quarantine_purge_days": <QuarantinePurgeItemsAfterDelay as integer or null>,
"scheduled_scan_day": "<Mapped ScheduledScanDay string or null>",
"scheduled_scan_time_of_day": "<ScheduledScanTime converted to HH:mm:ss or null>",
"scheduled_scan_type": "<Mapped ScanParameters string or null>",
"randomize_schedule_task_times": <RandomizeScheduleTaskTimes as boolean or null>,
"low_threat_action": "<Action string from ThreatIDDefaultAction_Ids[2] or null>",
"moderate_threat_action": "<Action string from ThreatIDDefaultAction_Ids[3] or null>",
"high_threat_action": "<Action string from ThreatIDDefaultAction_Ids[4] or null>",
"severe_threat_action": "<Action string from ThreatIDDefaultAction_Ids[5] or null>",
"asr_rules_state": { // Example JSON object structure
"<RuleGuid1>": "<State: 'Enabled'/'Audit'/'Disabled'>",
"<RuleGuid2>": "<State>"
},
"network_protection_level": "<Mapped EnableNetworkProtection string or null>",
"controlled_folder_access_state": "<Mapped EnableControlledFolderAccess string or null>",
"controlled_folder_access_protected_folders": ["<Path1>", "<Path2>", ...], // From Get-MpPreference -ControlledFolderAccessProtectedFolders
"controlled_folder_access_allowed_apps": ["<Path1>", "<Path2>", ...], // From Get-MpPreference -ControlledFolderAccessAllowedApplications
"excluded_processes": ["<Path1>", "<Path2>", ...], // From ExcludedProcesses property
"excluded_paths": ["<Path1>", "<Path2>", ...], // From ExcludedPaths property
"excluded_extensions": [".ext1", ".ext2", ...], // From ExcludedExtensions property
"signature_update_interval_hours": <SignatureUpdateInterval as integer or null>
}
**Error Handling:** If Get-MpPreference fails, output an empty JSON object {}. Handle errors retrieving individual properties gracefully (use null). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 13: Collect Detailed Audit Policy Settings
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect effective advanced audit policy settings per subcategory.
**Instructions:**
1. Execute the command `auditpol /get /category:*`.
2. Capture the standard output of this command.
3. Parse the text output. Identify the major Category lines and the subsequent Subcategory lines. For each Subcategory, extract the current auditing setting (e.g., 'No Auditing', 'Success', 'Failure', 'Success and Failure').
4. Map the parsed settings to the schema fields. Map the setting strings to the schema enum ('None', 'Success', 'Failure', 'Success and Failure', 'Unknown').
5. Output the data as a JSON array of objects, one per subcategory.
**Target Schema:** `DetailedAuditPolicySettings` table
**Output JSON Format (Array):**
```json
[
{
"policy_category": "<Parsed Category Name>",
"policy_subcategory": "<Parsed Subcategory Name>",
"auditing_flags": "<Mapped Auditing Setting Enum ('None', 'Success', 'Failure', 'Success and Failure', 'Unknown')>"
},
...
]
**Error Handling:** If the auditpol command fails or output cannot be parsed, output an empty JSON array []. Handle parsing errors robustly. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 14: Collect Individual Windows Firewall Rules
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate and collect details for all configured Windows Firewall rules.
**Instructions:**
1. Use the `Get-NetFirewallRule` PowerShell cmdlet.
2. For each rule, collect the following properties: `DisplayName`, `Group`, `Profile`, `Enabled`, `Direction`, `Action`, `Protocol`, `LocalPort`, `RemotePort`, `LocalAddress`, `RemoteAddress`, `Program`, `Service`, `Description`.
3. Map the collected properties directly to the corresponding JSON fields. Note that `Profile`, `LocalPort`, `RemotePort`, `LocalAddress`, `RemoteAddress`, `Program`, `Service` can contain arrays or specific string values like 'Any'. Represent arrays as JSON arrays of strings.
4. Output the data as a JSON array of objects, one per firewall rule.
**Target Schema:** `DeviceFirewallRules` table
**Output JSON Format (Array):**
```json
[
{
"rule_name": "<DisplayName>",
"group_name": "<Group or null>",
"profile_names": ["<Profile1>", "<Profile2>", ... or null], // Array from Profile property
"is_enabled": <Enabled as boolean>,
"direction": "<Direction string>",
"action": "<Action string>",
"protocol": "<Protocol string or null>",
"local_ports": "<LocalPort string or array or null>",
"remote_ports": "<RemotePort string or array or null>",
"local_addresses": "<LocalAddress string or array or null>",
"remote_addresses": "<RemoteAddress string or array or null>",
"program_path": "<Program string or null>",
"service_name": "<Service string or null>",
"description": "<Description or null>"
},
...
]
**Error Handling:** If the cmdlet fails, output an empty JSON array []. Handle missing properties for individual rules gracefully (use null). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 15: Collect Device Firewall Profile Settings
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect the configuration settings for the standard Windows Firewall profiles (Domain, Private, Public).
**Instructions:**
1. Use the `Get-NetFirewallProfile` PowerShell cmdlet.
2. By default, this cmdlet returns objects for Domain, Private, and Public profiles. Iterate through these profiles.
3. For each profile, collect its `Name`, `Enabled` status, `DefaultInboundAction`, `DefaultOutboundAction`, `AllowUnicastResponseToMulticast`, `NotifyOnListen`, `BlockAllInboundTraffic`.
4. Map the collected properties to the specified JSON output fields. Map the `Enabled` enum to a boolean `is_enabled`. Map `DefaultInboundAction` and `DefaultOutboundAction` enums directly to strings ('Allow', 'Block').
5. Output the data as a JSON array of objects, one object per profile.
**Target Schema:** `DeviceFirewallProfiles` table
**Output JSON Format (Array):**
```json
[
{
"profile_name": "<Name: 'Domain'/'Private'/'Public'>",
"is_enabled": <Mapped Enabled enum as boolean or null>,
"default_inbound_action": "<DefaultInboundAction string or null>",
"default_outbound_action": "<DefaultOutboundAction string or null>",
"allow_unicast_response": <AllowUnicastResponseToMulticast as boolean or null>,
"notify_on_listen": <NotifyOnListen as boolean or null>,
"block_all_inbound": <BlockAllInboundTraffic as boolean or null>
},
... // One object for each profile (Domain, Private, Public)
]
**Error Handling:** If the cmdlet fails, output an empty JSON array []. Handle missing properties for individual profiles gracefully (use null). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 16: Collect Device Drivers
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect information about installed device drivers.
**Instructions:**
1. Use a WMI query to retrieve driver details from the `Win32_PNPSignedDriver` class.
2. For each driver, collect `Description`, `Manufacturer` (maps to `driver_provider`), `DriverVersion`, `DriverDate`, `IsSigned`, `DeviceID` (maps to `pnp_device_id`), `InfName`, `DeviceName`.
3. Convert `DriverDate` (which is in WMI datetime format) to a standard Date format (e.g., YYYY-MM-DD).
4. Map the collected properties to the specified JSON output fields.
5. Output the data as a JSON array of objects, one per driver instance.
**Target Schema:** `DeviceDrivers` table
**Output JSON Format (Array):**
```json
[
{
"device_name": "<DeviceName or null>",
"pnp_device_id": "<DeviceID>",
"driver_provider": "<Manufacturer or null>",
"driver_version": "<DriverVersion or null>",
"driver_date": "<Converted DriverDate YYYY-MM-DD or null>",
"is_signed": <IsSigned as boolean or null>,
"inf_name": "<InfName or null>",
"driver_path": null // Not directly available in Win32_PNPSignedDriver
},
...
]
**Error Handling:** If the WMI query fails, output an empty JSON array []. Handle errors during date conversion or missing properties gracefully (use null). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 17: Collect Device Scheduled Tasks
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect information about scheduled tasks configured on the device.
**Instructions:**
1. Use the `Get-ScheduledTask` PowerShell cmdlet to retrieve all tasks.
2. For each task, collect the following properties: `TaskPath`, `TaskName`, `State`, `LastRunTime`, `LastTaskResult`, `NextRunTime`, `Actions`, `Triggers`, `Principal` (for `run_as_user`).
3. Combine `TaskPath` and `TaskName` to form the full `task_name` field.
4. Map the `State` enum to the `status` field (e.g., 'Ready', 'Running', 'Disabled'). Set `is_enabled` based on `State` not being 'Disabled'.
5. Extract the `UserId` from the `Principal` object for the `run_as_user` field.
6. Serialize the `Actions` and `Triggers` objects into JSON strings or extract key information (like executable path from `Actions`, schedule details from `Triggers`) to store in the respective JSON fields. Choose a consistent format for the JSON.
7. Output the data as a JSON array of objects, one per scheduled task.
**Target Schema:** `DeviceScheduledTasks` table
**Output JSON Format (Array):**
```json
[
{
"task_name": "<TaskPath + TaskName>",
"status": "<Mapped State string>",
"is_enabled": <(State != 'Disabled') as boolean>,
"last_run_time": "<LastRunTime UTC ISO8601 or null>",
"last_run_result": <LastTaskResult as integer or null>,
"next_run_time": "<NextRunTime UTC ISO8601 or null>",
"actions": [{ "type": "Exec", "path": "<Action.Execute>", "arguments": "<Action.Arguments>" }, ...], // Example structure for Actions JSON
"triggers": [{ "type": "Time", "startTime": "...", "interval": "..." }, ...], // Example structure for Triggers JSON
"run_as_user": "<Principal.UserId or null>"
},
...
]
**Error Handling:** If the cmdlet fails, output an empty JSON array []. Handle errors accessing properties or serializing objects gracefully (use null or empty structures). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 18: Implement Collector for General Hardware Sensor Readings (Temp/Fan/Volt)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect readings from common hardware sensors like temperatures, fan speeds, and voltages.
**Instructions:**
1. Attempt to collect temperature readings using WMI: `Get-CimInstance -Namespace root/WMI -ClassName MSAcpi_ThermalZoneTemperature`. Extract `CurrentTemperature` (convert from Kelvin to Celsius: `($_.CurrentTemperature / 10) - 273.15`) and `InstanceName` (for `sensor_name`). Set `sensor_type` to 'Temperature' and `reading_unit` to 'C'.
2. **Note:** Reliable collection of Fan Speed and Voltage often requires external libraries/tools like LibreHardwareMonitor/OpenHardwareMonitor or vendor-specific WMI providers which are NOT assumed here. This script should focus *only* on the WMI temperature method. If additional sensors are needed later, a separate task involving external dependencies would be required.
3. Format the collected temperature data into the specified JSON array format.
4. Output the data as a JSON array of objects.
**Target Schema:** `DeviceSensorReadings` table
**Output JSON Format (Array):**
```json
[
{
"sensor_type": "Temperature",
"sensor_name": "<InstanceName from WMI>",
"reading_value": <Converted Temperature in Celsius as float>,
"reading_unit": "C",
"status": null // WMI temp class doesn't provide status
},
... // One object per thermal zone found
]
**Error Handling:** If the WMI query fails or no sensors are found, output an empty JSON array []. Handle temperature conversion errors gracefully. The script should not crash.
**Provide only the PowerShell script code block for collecting temperature data via WMI.** Assume sufficient privileges.
Task 19: Implement Collector for Detailed Physical RAM Module Information
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect detailed information for each installed physical RAM module (memory stick).
**Instructions:**
1. Use a WMI query to retrieve details from the `Win32_PhysicalMemory` class.
2. For each memory module instance found, collect the following properties: `BankLabel` (for slot designation), `Capacity`, `FormFactor`, `MemoryType`, `Speed`, `Manufacturer`, `PartNumber`, `SerialNumber`.
3. Map the numeric `MemoryType` code to a descriptive string (Common values: 20=DDR, 21=DDR2, 22=DDR2 FB-DIMM, 24=DDR3, 26=DDR4, other values exist). Use 'Unknown' if the code is unmapped.
4. Map the numeric `FormFactor` code to a descriptive string (e.g., 8=DIMM, 9=SODIMM, 12=MiniDIMM). Use 'Unknown' if unmapped.
5. Format the collected data into a JSON array, where each object represents one RAM module.
**Target Schema:** `DeviceHardware.ram_details` (JSONB array)
**Output JSON Format (Array):**
```json
[
{
"Slot": "<BankLabel or null>",
"Capacity": <Capacity as integer or null>,
"Type": "<Mapped MemoryType string or null>", // DDR3, DDR4 etc.
"FormFactor": "<Mapped FormFactor string or null>", // DIMM, SODIMM etc.
"Speed": <Speed as integer or null>, // Speed in MHz
"Manufacturer": "<Manufacturer or null>",
"PartNumber": "<PartNumber or null>",
"SerialNumber": "<SerialNumber or null>"
},
...
]
**Error Handling:** If the WMI query fails or no memory modules are found, output an empty JSON array []. Handle missing properties for individual modules gracefully (use null). Handle numeric code mapping errors using 'Unknown'. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.**
Assume sufficient privileges.

Task 20: Enhance Network Adapter Collector for DHCP Lease, WINS, vSwitch
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script that enhances network adapter collection by adding DHCP lease details, WINS server configuration, and associated virtual switch name (if applicable). This builds upon collecting basic IP configuration.
**Instructions:**
1. Identify relevant network adapters (e.g., those that are IP-enabled, using WMI `Win32_NetworkAdapter` or PowerShell `Get-NetAdapter`).
2. For each relevant adapter (identified by its `InterfaceIndex` or `MACAddress`):
* Query WMI `Win32_NetworkAdapterConfiguration` using the adapter's `Index` property (`WHERE Index = <adapter_index>`).
* Collect `DHCPServer`, `DHCPLeaseObtained`, `DHCPLeaseExpires`, `WINSPrimaryServer`, `WINSSecondaryServer`. Convert WMI datetime strings (`DHCPLeaseObtained`, `DHCPLeaseExpires`) to UTC ISO8601 format. Combine `WINSPrimaryServer` and `WINSSecondaryServer` into a string array.
* Attempt to identify the associated virtual switch name using PowerShell: `Get-VMNetworkAdapter -ManagementOS | Where-Object {$_.MacAddress -eq '<adapter_mac_address>'} | Select-Object -ExpandProperty SwitchName`. This only applies if the host is a Hyper-V server and the adapter is associated with a vSwitch. Handle errors if the cmdlet/module is not available or if no match is found.
3. Merge these collected details with the basic adapter information (Name, MAC, IPs, etc., assumed collected separately) based on the adapter identifier (e.g., MAC address or Interface Index).
4. Output the *enhanced* data as a JSON array of objects, one per network adapter, including the new fields.
**Target Schema:** `DeviceNetworkAdapters` table (Adding `dhcp_server`, `dhcp_lease_obtained`, `dhcp_lease_expires`, `wins_servers`, `virtual_switch_name`)
**Output JSON Format (Array - showing only *added* fields for clarity):**
```json
[
{
// ... existing adapter fields (name, macAddress, ipAddresses etc.) ...
"dhcp_server": "<DHCPServer IP or null>",
"dhcp_lease_obtained": "<Lease Obtained UTC ISO8601 or null>",
"dhcp_lease_expires": "<Lease Expires UTC ISO8601 or null>",
"wins_servers": ["<WINSPrimaryServer or null>", "<WINSSecondaryServer or null>"], // Filter out nulls if desired
"virtual_switch_name": "<SwitchName from Get-VMNetworkAdapter or null>"
// ... other adapter fields ...
},
...
]
**Error Handling:** Handle WMI query failures gracefully. Handle errors if Get-VMNetworkAdapter fails or returns no result (set virtual_switch_name to null). If DHCP is not enabled, DHCP fields will likely be null or empty from WMI; handle this. If WINS is not configured, WINS fields will be null. If base adapter collection fails, output [].
**Provide only the PowerShell script code block for collecting only the additional DHCP, WINS, and vSwitch data, assuming basic adapter info is collected elsewhere.**
Assume sufficient privileges and potential need for Hyper-V/RemoteDesktopServices modules.
Task 21: Implement Collector for Disk Encryption Status (BitLocker)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect the encryption status for logical volumes managed by BitLocker.
**Instructions:**
1. Use the `Get-BitLockerVolume` PowerShell cmdlet.
2. Iterate through each volume returned by the cmdlet.
3. For each volume, collect the following properties: `MountPoint`, `VolumeStatus` (enum), `ProtectionStatus` (enum), `EncryptionPercentage`, `LockStatus` (enum), `KeyProtector` (array of objects).
4. Map the `VolumeStatus` enum to the schema `encryption_status` string ('FullyEncrypted', 'FullyDecrypted', 'EncryptionInProgress', 'DecryptionInProgress', etc.). Default to 'Unknown'.
5. Map the `ProtectionStatus` enum to the schema `protection_status` string ('On', 'Off', 'Unknown').
6. Extract the *type* string (e.g., 'Tpm', 'RecoveryPassword', 'PasswordProtector', 'StartupKey') from each object in the `KeyProtector` array and store these strings in the `protector_types` array.
7. Set `encryption_method` to 'BitLocker'.
8. Output the data as a JSON array of objects, one per volume managed by BitLocker. Include the `MountPoint` for server-side linking to the `DeviceLogicalDisks` table. **Do NOT attempt to collect or output recovery keys.**
**Target Schema:** `DeviceDiskEncryptionStatus` table
**Output JSON Format (Array):**
```json
[
{
"MountPoint": "<Volume MountPoint e.g., 'C:'>", // For server-side linking
"encryption_method": "BitLocker",
"encryption_status": "<Mapped VolumeStatus string>",
"protection_status": "<Mapped ProtectionStatus string>",
"percent_encrypted": <EncryptionPercentage as integer or null>,
"lock_status": "<Mapped LockStatus string or null>",
"protector_types": ["<Type1>", "<Type2>", ...] // Array of strings like 'Tpm', 'RecoveryPassword'
},
...
]
**Error Handling:** If Get-BitLockerVolume fails (e.g., BitLocker feature not installed or service stopped), output an empty JSON array []. Handle errors mapping enum values gracefully (use 'Unknown' or null). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 22: Implement Collector for Battery Status and Health
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect information about the device's battery, if one is present.
**Instructions:**
1. Use a WMI query to retrieve battery details from the `Win32_Battery` class. Check if any instances are returned.
2. If a battery is found (typically only one primary battery), collect the following properties: `Name` (for caption), `Description`, `BatteryStatus` (numeric code), `EstimatedChargeRemaining`, `EstimatedRunTime`, `FullChargeCapacity` (mWh), `DesignCapacity` (mWh), `Chemistry` (numeric code).
3. Map the numeric `BatteryStatus` code to a descriptive string (e.g., 1='Discharging', 2='AC Power/Unknown', 3='Fully Charged', 4='Low', 5='Critical', 6='Charging', 7='Charging/High', 8='Charging/Low', 9='Charging/Critical', 10='Undefined', 11='Partially Charged'). Use 'Unknown' if unmapped.
4. Map the numeric `Chemistry` code to a descriptive string (e.g., 1='Other', 2='Unknown', 3='Lead Acid', 4='Nickel Cadmium', 5='Nickel Metal Hydride', 6='Lithium-ion', 7='Zinc air', 8='Lithium Polymer'). Use 'Unknown' if unmapped.
5. Calculate a basic `health_status` string based on the ratio of `FullChargeCapacity` to `DesignCapacity` (e.g., >80% = 'Good', 50-80% = 'Fair', <50% = 'Poor'), if both values are present and positive. Otherwise, set to `null`.
6. Output the data as a JSON array containing a single object if a battery is found, or an empty array if no battery is detected.
**Target Schema:** `DeviceBattery` table
**Output JSON Format (Array with zero or one object):**
```json
[ // Empty array [] if no battery detected
{
"caption": "<Name or null>",
"description": "<Description or null>",
"battery_status_enum": "<Mapped BatteryStatus string>",
"charge_remaining_percent": <EstimatedChargeRemaining as integer or null>,
"estimated_runtime_minutes": <EstimatedRunTime as integer or null>,
"full_charge_capacity_mwh": <FullChargeCapacity as integer or null>,
"design_capacity_mwh": <DesignCapacity as integer or null>,
"chemistry": "<Mapped Chemistry string>",
"health_status": "<Calculated 'Good'/'Fair'/'Poor' or null>"
// Other WMI fields like TimeOnBattery can be added if needed by schema
}
]
**Error Handling:** If the WMI query fails or returns no instances, output []. Handle missing properties or calculation errors gracefully (use null). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 23: Implement Collector for Basic OS Upgrade History
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect information about the *last* Operating System upgrade by reading specific registry keys. This provides limited historical data.
**Instructions:**
1. Define the registry key path: `HKLM:\SYSTEM\Setup\Source OS`.
2. Use `Test-Path` to check if the key exists.
3. If the key exists, use `Get-ItemProperty -Path <keypath>` to read the values: `ProductName`, `EditionID`, `ReleaseId` (check existence), `CurrentBuildNumber`.
4. Attempt to get an approximate timestamp by reading the last write time of the parent `HKLM:\SYSTEM\Setup` key: `(Get-Item 'Registry::HKLM\SYSTEM\Setup').LastWriteTimeUtc`. Convert this to UTC ISO8601 format. Note this is only an approximation of the upgrade time.
5. Map the collected data to the specified JSON fields. Set `install_type` to 'Upgrade'.
6. Output the data as a single JSON object. If the `Source OS` key does not exist, output an empty JSON object `{}`.
**Target Schema:** `OsUpgradeHistory` table (This represents one potential entry)
**Output JSON Format (Single Object):**
```json
{
"product_name": "<ProductName value or null>",
"edition": "<EditionID value or null>",
"release_id": "<ReleaseId value or null>", // Handle if value doesn't exist
"install_timestamp_utc": "<Approximated Timestamp UTC ISO8601 or null>",
"install_type": "Upgrade",
"system_root": null // Not available here
}
// Output {} if HKLM:\SYSTEM\Setup\Source OS does not exist
**Error Handling:** Use Test-Path and handle Get-ItemProperty errors gracefully (e.g., if a value doesn't exist). If the primary key doesn't exist, output {}. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 24: Enhance Startup Items Collector for Publisher
You are an expert Windows system administrator and scripter. Your task is to enhance the collection of startup items by adding the Publisher information derived from the executable's digital signature.
**Instructions:**
1. First, collect the basic startup item information (Name, Executable Path/Command, Location, User Context) from standard locations (Registry Run/RunOnce keys for HKLM/HKCU, All Users/Current User Startup Folders). Focus on HKLM and All Users locations when running as System.
2. For each startup item found:
* Identify the `executablePath` (may need parsing from the command string).
* Use `Get-AuthenticodeSignature -FilePath <executablePath>` within a `try/catch` block. This command checks the digital signature.
* If successful and a signature exists (`Status -eq 'Valid'`), access the `SignerCertificate`. Extract the Subject Name string.
* Parse the Subject Name string to find the Organization (`O=...`) or Common Name (`CN=...`) field. Use this value as the `publisher`. Prioritize `O=` if available. Handle variations in subject format.
* If `Get-AuthenticodeSignature` fails, the file is unsigned (`Status -ne 'Valid'`), or the subject name cannot be parsed effectively, set `publisher` to `null`.
3. Combine the collected publisher information with the basic startup item details.
4. Output the data as a JSON array of objects, one per startup item, including the new `publisher` field.
**Target Schema:** `DeviceStartupItems` table (adding `publisher`)
**Output JSON Format (Array):**
```json
[
{
"item_name": "<Name>",
"command_line": "<Executable Path or Command>",
"startup_type": "<Source Location String>",
"user_context": "<'System' or User SID/Name>",
"publisher": "<Extracted Publisher Name or null>"
// Other fields like status, is_running deferred
},
...
]
**Error Handling:** Implement try/catch for Get-AuthenticodeSignature as it can fail for various reasons (file not found, no signature, access denied, slow network access for CRL checks). Ensure failure for one item doesn't stop collection for others. Output [] if no startup items are found.
**Provide only the PowerShell script code block for collecting startup items with the added publisher check.** Assume sufficient privileges.
Task 25: Implement Collector for Local User Profile Details
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect basic information about local user profiles, focusing on path, status, and last use time.
**Instructions:**
1. Use a WMI query to retrieve profile details from the `Win32_UserProfile` class.
2. For each profile instance returned, collect the `SID`, `LocalPath`, `Status` (numeric flags), and `LastUseTime`.
3. Map the numeric `Status` flags to a descriptive string. Key flags: 1=Temporary, 2=Roaming, 4=Mandatory, 8=Corrupt. If multiple flags are set, combine descriptions (e.g., 'Roaming, Mandatory') or prioritize. If Status is 0, use 'OK'. Default to 'Unknown' if mapping fails or status is unexpected.
4. Convert the `LastUseTime` property (WMI datetime format) to UTC ISO8601 format string.
5. Map the collected and processed data to the specified JSON fields. Set deferred fields to `null`.
6. Output the data as a JSON array of objects, one per user profile.
**Target Schema:** `LocalUserProfiles` table
**Output JSON Format (Array):**
```json
[
{
"account_sid": "<SID string>",
"profile_path": "<LocalPath or null>",
"size_bytes": null, // Deferred
"status": "<Mapped Status string (e.g., 'OK', 'Roaming', 'Temporary')>",
"last_used_time_utc": "<LastUseTime UTC ISO8601 or null>",
"last_logon": null, // Deferred
"logon_count": null, // Deferred
"bad_password_count": null, // Deferred
"password_age_seconds": null, // Deferred
"account_expires": null // Deferred
},
...
]
**Error Handling:** If the WMI query fails, output an empty JSON array []. Handle errors converting dates or mapping status codes gracefully (use null or 'Unknown'). The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 26: Implement Collector for Installed Browsers
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to identify installed instances of Microsoft Edge, Google Chrome, and Mozilla Firefox, including their version and installation path.
**Instructions:**
1. Define the target browsers and their potential registry keys or executable names (e.g., 'Microsoft Edge'/'msedge.exe', 'Google Chrome'/'chrome.exe', 'Mozilla Firefox'/'firefox.exe').
2. Check standard installation paths (`Program Files`, `Program Files (x86)`) and potentially user-specific paths (`%LOCALAPPDATA%`) for browser executables.
3. Check registry `HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\` for browser executables to find their paths.
4. For each potentially found browser executable:
* Verify the file exists.
* Use `(Get-Item <path>).VersionInfo.ProductVersion` or `FileVersion` to get the `version`.
* Record the `browser_name` based on the executable/path found.
* Record the full `install_path` to the executable.
5. Attempt to determine the system `is_default` HTTP/HTTPS handler by querying `HKCR\http\shell\open\command` and `HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice` (requires careful parsing and may be limited running as System). Set to `null` if uncertain.
6. Deduplicate findings (e.g., based on install path).
7. Output the data as a JSON array of objects, one per unique browser installation detected.
**Target Schema:** `DeviceBrowsers` table
**Output JSON Format (Array):**
```json
[
{
"browser_name": "<'Microsoft Edge'/'Google Chrome'/'Mozilla Firefox'>",
"version": "<File Version string or null>",
"install_path": "<Full path to main executable or null>",
"is_default": <boolean or null>
},
...
]
**Error Handling:** Handle errors accessing file system or registry. If version info cannot be retrieved, use null. If default status is uncertain, use null. Output [] if no supported browsers are found.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 27: Enhance Endpoint Protection Collector for Engine Version
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect the specific Antivirus Engine Version, enhancing basic AV status collection.
**Instructions:**
1. Assume basic AV product info (Name, Vendor, etc.) is collected via WMI `AntivirusProduct` class (as in previous outputs).
2. For each detected AV product:
* **If 'Windows Defender':** Execute `(Get-MpComputerStatus).AntivirusEngineVersion`. Capture the output.
* **If other AV:** Define logic for known major AVs if possible (e.g., check specific registry keys like `HKLM\SOFTWARE\<Vendor>\<Product>\EngineVersion`). If no specific logic exists for a vendor, set engine version to `null`.
3. Merge the collected `engine_version` with the basic AV product information based on the product name.
4. Output the *complete* data for each AV product (including the new engine version) as a JSON array.
**Target Schema:** `EndpointProtectionStatus` table (Adding `engine_version`)
**Output JSON Format (Array - Showing structure):**
```json
[
{
"name": "<ProductName>",
// ... other existing AV fields ...
"engineVersion": "<Collected Engine Version or null>" // **ADDED FIELD**
},
...
]
**Error Handling:** Wrap Get-MpComputerStatus and any vendor-specific checks in try/catch. If engine version collection fails for a product, set its engineVersion field to null. If base AV collection fails, output [].
**Provide only the PowerShell script code block specifically for getting the engine version and merging it with assumed base AV data.** Assume sufficient privileges.
Task 28: Implement Collector for Sound Device Information
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect basic information about installed sound devices.
**Instructions:**
1. Use a WMI query to retrieve sound device details from the `Win32_SoundDevice` class.
2. For each device found, collect `Name` and `Manufacturer`.
3. Output the data as a JSON array of objects, one object per sound device.
**Target Schema:** `DeviceHardware.sound_devices` (JSONB array)
**Output JSON Format (Array):**
```json
[
{
"name": "<Name>",
"manufacturer": "<Manufacturer or null>"
},
...
]
**Error Handling:** If the WMI query fails or no devices are found, output an empty array []. Handle missing properties using null.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 29: Implement Collector for Network Shares Hosted on Device (Basic Info)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate network shares hosted *by this local machine* and collect basic details.
**Instructions:**
1. Use a WMI query to retrieve share details from the `Win32_Share` class.
2. For each share instance, collect `Name`, `Path`, `Caption` (map to description), `Type` (numeric), and `MaximumAllowed`.
3. Map the numeric `Type` code to a descriptive string: 0='Disk', 1='Printer', 2='Device', 3='IPC', 2147483651='Special'. Use 'Unknown' if unmapped.
4. Map `MaximumAllowed` to `max_users`. A value of -1 typically means unlimited; represent as `null` or keep -1 based on schema preference (using null here).
5. Output the data as a JSON array of objects, one per hosted share.
**Target Schema:** `NetworkShares` table
**Output JSON Format (Array):**
```json
[
{
"share_name": "<Name>",
"path": "<Path>",
"description": "<Caption or null>",
"share_type": "<Mapped Type string>",
"max_users": <MaximumAllowed as integer or null if -1>
},
...
]
**Error Handling:** If the WMI query fails, output an empty JSON array []. Handle Type mapping errors using 'Unknown'. Handle missing properties using null.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 30: Implement Collector for Hosted Network Share Permissions
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect share-level permissions (ACLs) for network shares hosted on the local device. This script depends on identifying shares using WMI (`Win32_Share`).
**Instructions:**
1. Use WMI to get all instances of `Win32_Share`.
2. For each `Win32_Share` instance, retrieve its `Name`.
3. Use the share `Name` to get the corresponding `Win32_LogicalShareSecuritySetting` instance (e.g., `Get-CimInstance -ClassName Win32_LogicalShareSecuritySetting -Filter "Name='<ShareName>'" `).
4. Invoke the `GetSecurityDescriptor` method on the `Win32_LogicalShareSecuritySetting` object.
5. Parse the `Descriptor.DACL` property from the returned security descriptor object. This DACL is an array of ACEs (Access Control Entries).
6. For each ACE (Access Control Entry) in the DACL:
* Extract the Trustee's `SID` string.
* Extract the Trustee's `Name` (requires resolving the SID, potentially using `(New-Object System.Security.Principal.SecurityIdentifier($_.Trustee.SID)).Translate([System.Security.Principal.NTAccount]).Value`). Handle errors during resolution.
* Determine the `access_type`: 'Allow' if `AceType` is 0, 'Deny' if `AceType` is 1.
* Determine the basic `permission` based on `AccessMask` bits. Common values: 2032127 = FullControl, 1245631 = Change, 1179817 = Read. Create a mapping for these standard permissions. If the mask doesn't match these, use 'Custom' or skip.
7. Map the collected details for each ACE to the `SharePermissions` JSON structure, linking it back to the `network_share_id` (which will be generated server-side based on device_id and share_name). For the output, use the `share_name` as a temporary identifier.
8. Output the data as a JSON array of objects, one object per ACE per share.
**Target Schema:** `SharePermissions` table
**Output JSON Format (Array):**
```json
[
{
"share_name": "<Name of the Share>", // Temporary identifier for server-side linking
"account_name": "<Resolved Trustee Name or SID if resolution failed>",
"account_sid": "<Trustee SID string>",
"access_type": "<'Allow' or 'Deny'>",
"permission": "<'Read' or 'Change' or 'FullControl' or 'Custom'>"
},
... // Repeat for every ACE on every share
]
**Error Handling:** If WMI queries fail, GetSecurityDescriptor fails, or SID resolution fails, log the error internally or skip the problematic item gracefully. Output an empty array [] if no shares or permissions can be retrieved. The script should not crash. Security descriptor parsing is complex; handle potential variations and errors robustly.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges (Admin required for security descriptors).
Task 31: Implement Collector for Mapped Network Drives (Registry Method)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate mapped network drives by reading user registry hives. This is an advanced task requiring careful registry manipulation.
**Instructions:**
1. Identify loaded user profiles/SIDs, for example using WMI `SELECT SID, LocalPath FROM Win32_UserProfile WHERE Loaded = True`.
2. For each loaded user profile SID:
* Attempt to load the user's registry hive (`NTUSER.DAT` located within the `LocalPath`) into a temporary registry key (e.g., `HKU\<SID>_temp`) using `reg load HKU\<SID>_temp "<PathToNTUserDAT>"`. This requires Administrator privileges. Handle potential errors (e.g., hive already loaded, permissions issues, locked file).
* If the hive loads successfully, query the `Network` subkey under the loaded hive (e.g., `Registry::HKEY_USERS\<SID>_temp\Network`).
* Iterate through the subkeys named after drive letters (e.g., 'F', 'G', 'Z').
* For each drive letter subkey, read the `RemotePath` value, which contains the UNC path.
* Store the User SID, Drive Letter (append ':'), and RemotePath (UNC).
* **Crucially**, ensure the temporary hive is unloaded using `reg unload HKU\<SID>_temp` in a `finally` block or similar construct to prevent registry corruption.
3. Map the collected data to the specified JSON format.
4. Output the data as a JSON array of objects, one per mapped drive per user session.
**Target Schema:** `MappedNetworkDrives` table
**Output JSON Format (Array):**
```json
[
{
"user_sid": "<User SID string>",
"drive_letter": "<DriveLetter: e.g., 'Z:'>",
"provider_name": "<RemotePath (UNC)>"
// Other fields like size/filesystem are not available via this method
},
...
]
**Error Handling:** This method is prone to errors (permissions, locked hives). Implement robust try/catch blocks for loading/unloading hives and reading registry values. If errors occur for a specific user, skip that user and continue. If no drives are found, output an empty array []. The script must ensure hives are unloaded even if errors occur.
**Provide only the PowerShell script code block for collecting this data.** Assume Administrator privileges.
Task 32: Implement Collector for Windows Activation Status
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to determine the Windows activation status and retrieve the partial product key.
**Instructions:**
1. Use a WMI query against the `SoftwareLicensingProduct` class.
2. Filter for the Windows product using its Application ID: `WHERE ApplicationId = '55c92734-d682-4d71-983e-d6ec3f16059f'`. Also filter `WHERE PartialProductKey IS NOT NULL` to target the relevant license instance.
3. Collect the `LicenseStatus` and `PartialProductKey` properties.
4. Map the numeric `LicenseStatus` code to a descriptive string enum ('Unlicensed'=0, 'Licensed'=1, 'OOBGrace'=2, 'OOTGrace'=3, 'NonGenuineGrace'=4, 'Notification'=5, 'ExtendedGrace'=6, default 'Unknown').
5. Output the data as a single JSON object.
**Target Schema:** `DeviceSoftware` table (These fields will be linked server-side to the specific Windows software entry based on the device)
**Output JSON Format (Single Object):**
```json
{
"detected_activation_status": "<Mapped LicenseStatus string or 'Unknown'>",
"detected_license_key": "<PartialProductKey or null>"
}
**Error Handling:** If the WMI query fails or returns no results matching the filter, output a JSON object with null values: {"detected_activation_status": null, "detected_license_key": null}. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges.
Task 33: Implement Collector for Browser Policy Configuration (Registry Method)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect policy-enforced configuration settings for Microsoft Edge, Google Chrome, and Mozilla Firefox from standard Group Policy registry locations.
**Instructions:**
1. Define the base registry paths for policies:
* Edge Machine: `HKLM:\Software\Policies\Microsoft\Edge`
* Edge User: `HKCU:\Software\Policies\Microsoft\Edge`
* Chrome Machine: `HKLM:\Software\Policies\Google\Chrome`
* Chrome User: `HKCU:\Software\Policies\Google\Chrome`
* Firefox Machine: `HKLM:\Software\Policies\Mozilla\Firefox`
* Firefox User: `HKCU:\Software\Policies\Mozilla\Firefox`
2. For each path:
* Check if the path exists using `Test-Path`.
* If it exists, use `Get-ItemProperty -Path <path>` to retrieve all registry values (settings) directly under that key.
* Iterate through the retrieved property names and values (excluding PS* properties).
* Determine the `browser_name` ('Edge', 'Chrome', 'Firefox') and `user_context` ('MachinePolicy' for HKLM, 'UserPolicy' for HKCU) based on the path being processed.
* Map the registry value name to a standardized `setting_name` (initially, just use the registry value name; server-side mapping might be needed later). Store the registry value data as a string in `setting_value`.
* Set `source` to 'Policy'.
3. Aggregate all found settings into a single JSON array.
4. Output the data as a JSON array of objects, one per discovered policy setting.
**Target Schema:** `BrowserConfiguration` table
**Output JSON Format (Array):**
```json
[
{
"browser_name": "<'Edge'/'Chrome'/'Firefox'>",
"user_context": "<'MachinePolicy'/'UserPolicy'>",
"setting_name": "<Registry Value Name>",
"setting_value": "<Registry Value Data as string>",
"source": "Policy"
},
... // One object per setting found in any policy location
]
**Error Handling:** Use Test-Path to avoid errors for non-existent keys. Handle potential errors during registry access gracefully. If no policy settings are found, output an empty JSON array []. The script should not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume sufficient privileges (including access to HKLM and potentially HKCU if running as System needs to access specific user hives, though typically GPO user policies apply directly to HKCU accessible by System).
Task 34: Implement Collector for Browser Extensions (Multi-Browser, User Context Aware)
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to enumerate installed extensions for Microsoft Edge, Google Chrome, and Mozilla Firefox across *all available user profiles* on the device. This is a complex task requiring interaction with user profile data.
**Instructions:**
1. Identify user profiles on the system, focusing on their SIDs and local profile paths (e.g., via WMI `Win32_UserProfile`).
2. For each user profile:
* Construct the expected paths to the extensions directories or preference files for Edge, Chrome, and Firefox within that user's profile (e.g., `C:\Users\<User>\AppData\Local\Microsoft\Edge\User Data\Default\Extensions`, `...\Google\Chrome\User Data\Default\Extensions`, `...\Mozilla\Firefox\Profiles\<ProfileName>\extensions.json`). Note: There can be multiple browser profiles (`Profile 1`, `Profile 2`, etc.) within `User Data`. The script should attempt to check 'Default' and potentially other numbered profiles if feasible.
* **Edge/Chrome (Manifest V3):**
* Enumerate subdirectories within the `Extensions` folder. Each subdirectory name is the `extension_id`.
* Within each extension's versioned subdirectory, locate and parse the `manifest.json` file.
* Extract `name`, `version`, `description` (if available).
* Determine `is_enabled` status by checking browser preference files (e.g., 'Preferences' or 'Secure Preferences' JSON file in the profile root) which store extension states (complex parsing required, might be difficult/unreliable; default to `null` if state cannot be reliably determined).
* **Firefox:**
* Locate and parse the `extensions.json` file within the Firefox profile directory.
* Iterate through the `addons` array.
* Extract `id` (extension_id), `name`, `version`, `active` (is_enabled), `defaultLocale.description`.
* Store the User SID as the `user_context`.
* Link back to the appropriate browser instance collected in Task 22 using the browser name/path (requires server-side linking logic). For this script's output, include the browser name.
3. Aggregate results from all found browsers and user profiles.
4. Output the data as a JSON array of objects, one per discovered extension instance per user profile per browser.
**Target Schema:** `BrowserExtensions` table
**Output JSON Format (Array):**
```json
[
{
"browser_name": "<'Edge'/'Chrome'/'Firefox'>", // For server-side linking
"user_context": "<User SID string>",
"extension_id": "<Extension ID>",
"name": "<Extension Name or null>",
"version": "<Extension Version or null>",
"is_enabled": <boolean or null if cannot determine>,
"install_path": "<Full path to extension folder or null>"
},
...
]
**Error Handling:** This task is highly complex and prone to errors due to: varying profile locations, browser updates changing structures, file access permissions (especially if not running as the user), and complex JSON parsing for state. Implement extensive try/catch blocks. If a profile or browser path doesn't exist, skip it. If parsing fails for an extension, skip it. If no extensions are found, output an empty array []. The script must be robust against these issues and not crash.
**Provide only the PowerShell script code block for collecting this data.** Assume Administrator privileges are available to access user profile directories. The reliability of determining the 'enabled' state, especially for Chrome/Edge, might be limited when running as System.
Task 35: Enhance Process Collector for Parent PID and Start Time
You are an expert Windows system administrator and scripter. Your task is to enhance the collection of running processes to include the Parent Process ID and the process Start Time.
**Instructions:**
1. Use the `Get-Process` PowerShell cmdlet. Include the `-IncludeUserName` parameter.
2. For each process, collect:
* `Id` (processId)
* `ProcessName` (name)
* `Path` (executablePath - handle access denied errors)
* `CommandLine` (Requires WMI `Win32_Process` query using the Process ID: `Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $($process.Id)" | Select-Object -ExpandProperty CommandLine`)
* `UserName`
* `Responding` status (for state)
* `StartTime` (convert to UTC ISO8601 format)
* CPU usage (`CPU` property from Get-Process)
* Working Set Memory (`WorkingSet64` for memoryBytes)
* **Parent Process ID:** Use a calculated property or a separate WMI query: `(Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = $($process.Id)").ParentProcessId`
3. Map these details to the `Processes` JSON structure.
4. Output the data as a JSON array of objects, one per running process.
**Target Schema:** `DeviceProcesses` table (Assumes schema exists or fields added to existing Process collector)
**Output JSON Format (Array):**
```json
[
{
"processId": <Id as integer>,
"name": "<ProcessName>",
"executablePath": "<Path or null>",
"commandLine": "<CommandLine from WMI or null>",
"userName": "<UserName or null>",
"cpuPercent": <CPU as float or null>,
"memoryBytes": <WorkingSet64 as integer or null>,
"state": "<'Running' if Responding, 'Not Responding' if not>",
"startTime": "<StartTime UTC ISO8601 or null>",
"parentPid": <ParentProcessId from WMI or null>
},
...
]
**Error Handling:** Handle errors getting Path, CommandLine, or ParentProcessId (e.g., for System Idle Process, access denied) using null. Handle StartTime errors. If Get-Process fails, output [].
**Provide only the PowerShell script code block.** Assume sufficient privileges.

Task 36 (Replaces original Open Ports task): Collect Network Connections Snapshot per Process
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect a *snapshot* of current TCP and UDP network connections, linking them to the owning Process ID. This replaces simple open port listening.
**Instructions:**
1. Use the `Get-NetTCPConnection` PowerShell cmdlet to get TCP connection details.
2. Use the `Get-NetUDPEndpoint` PowerShell cmdlet to get UDP listening endpoints.
3. For each TCP connection:
* Collect `LocalAddress`, `LocalPort`, `RemoteAddress`, `RemotePort`, `State`, `OwningProcess` (PID).
* Set `Protocol` to 'TCP'.
4. For each UDP endpoint:
* Collect `LocalAddress`, `LocalPort`.
* Set `RemoteAddress`, `RemotePort` to representative values (e.g., '::', 0 or '*',*).
* Set `State` to 'Listening' (or similar appropriate term).
* Collect `OwningProcess` (PID).
* Set `Protocol` to 'UDP'.
5. Combine TCP and UDP results.
6. Format the data into the specified JSON array, ensuring the `processID` is included.
**Target Schema:** Potentially a new table like `DeviceNetworkConnectionsSnapshot` or adapt `DeviceOpenPorts`. Includes PID linkage. Does *not* include aggregated bytes/packets.
**Output JSON Format (Array):**
```json
[
{
"protocol": "<'TCP' or 'UDP'>",
"localAddress": "<Local IP Address>",
"localPort": <Local Port as integer>,
"remoteAddress": "<Remote IP Address or '*'>",
"remotePort": <Remote Port as integer or 0>,
"state": "<TCP State string or 'Listening'>",
"processID": <OwningProcess PID as integer>
},
... // One object per TCP connection and UDP endpoint
]
**Error Handling:** If Get-NetTCPConnection or Get-NetUDPEndpoint fail, output an empty JSON array []. Handle errors getting properties for individual connections/endpoints gracefully.
**Provide only the PowerShell script code block.** Assume sufficient privileges.
Task 37: Collect Aggregate Network Interface Statistics
You are an expert Windows system administrator and scripter. Your task is to create a PowerShell script to collect aggregate network statistics (Bytes/Packets In/Out, Errors, Discards) per network interface over a defined interval (the interval itself is managed externally, this script just collects current counter values).
**Instructions:**
1. Identify active network interfaces using `Get-NetAdapter | Where-Object {$_.Status -eq 'Up'}`. Note their `InterfaceDescription` or `Name`.
2. Use the `Get-Counter` cmdlet to retrieve the *current values* of relevant performance counters for each active interface from the `\Network Interface(*)` performance object set.
3. Target Counters (use interface name/description from step 1 in the path):
* `\Network Interface(<Interface Name/Desc>)\Bytes Received/sec`
* `\Network Interface(<Interface Name/Desc>)\Bytes Sent/sec`
* `\Network Interface(<Interface Name/Desc>)\Packets Received/sec`
* `\Network Interface(<Interface Name/Desc>)\Packets Sent/sec`
* `\Network Interface(<Interface Name/Desc>)\Packets Received Errors`
* `\Network Interface(<Interface Name/Desc>)\Packets Outbound Errors`
* `\Network Interface(<Interface Name/Desc>)\Packets Received Discarded`
* `\Network Interface(<Interface Name/Desc>)\Packets Outbound Discarded`
* *(Optional but related: `\Network Interface(<Interface Name/Desc>)\Output Queue Length`)*
4. Collect the `CookedValue` for each counter. Note that the "/sec" counters provide a rate, not a total count since boot. For interval totals, the server-side would need to calculate the delta between two collections. This script reports the *current* counter value or rate.
5. Format the collected data into a JSON array, one object per interface. Include the interface name/description for identification.
**Target Schema:** `NetworkPortMetrics` (or similar aggregate table). Note the schema expects *totals*, while counters often provide rates or cumulative totals. This script provides the *current* counter value. Server-side logic is needed for deltas/interval totals.
**Output JSON Format (Array):**
```json
[
{
"interface_name": "<Interface Name or Description>",
"bytes_received_per_sec": <CookedValue as float or null>,
"bytes_sent_per_sec": <CookedValue as float or null>,
"packets_received_per_sec": <CookedValue as float or null>,
"packets_sent_per_sec": <CookedValue as float or null>,
"packets_received_errors_total": <CookedValue as integer or null>, // This is cumulative
"packets_outbound_errors_total": <CookedValue as integer or null>, // This is cumulative
"packets_received_discarded_total": <CookedValue as integer or null>, // This is cumulative
"packets_outbound_discarded_total": <CookedValue as integer or null> // This is cumulative
},
... // One object per active network interface
]
** Error Handling:** If Get-Counter fails or specific counters are unavailable for an interface, report null for those values. If no active interfaces are found, output [].
** Provide only the PowerShell script code block.** Assume sufficient privileges. Emphasize that this collects currentcounter values/rates, not interval totals.