1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
Add-Type -Path "C:\Libs\System.Data.SQLite.dll"
function Get-SqliteConnection { param([string]$DatabasePath)
if (-not (Test-Path (Split-Path $DatabasePath))) { New-Item (Split-Path $DatabasePath) -ItemType Directory -Force | Out-Null }
$connectionString = "Data Source=$DatabasePath;Version=3;Journal Mode=WAL;" $connection = New-Object System.Data.SQLite.SQLiteConnection $connection.ConnectionString = $connectionString $connection.Open() return $connection }
$dbPath = "C:\Data\Operations.db" $conn = Get-SqliteConnection -DatabasePath $dbPath
$createTableSql = @" CREATE TABLE IF NOT EXISTS ServerMetrics ( Id INTEGER PRIMARY KEY AUTOINCREMENT, ServerName TEXT NOT NULL, MetricName TEXT NOT NULL, Value REAL, Unit TEXT, Timestamp TEXT NOT NULL );
CREATE TABLE IF NOT EXISTS AuditLog ( Id INTEGER PRIMARY KEY AUTOINCREMENT, Action TEXT NOT NULL, Target TEXT, User TEXT, Timestamp TEXT NOT NULL, Details TEXT );
CREATE INDEX IF NOT EXISTS idx_metrics_server ON ServerMetrics(ServerName); CREATE INDEX IF NOT EXISTS idx_metrics_time ON ServerMetrics(Timestamp); CREATE INDEX IF NOT EXISTS idx_audit_time ON AuditLog(Timestamp); "@
$cmd = $conn.CreateCommand() $cmd.CommandText = $createTableSql $cmd.ExecuteNonQuery() Write-Host "数据库初始化完成:$dbPath" -ForegroundColor Green
function Add-Metric { param( [System.Data.SQLite.SQLiteConnection]$Connection, [string]$ServerName, [string]$MetricName, [double]$Value, [string]$Unit = "" )
$cmd = $Connection.CreateCommand() $cmd.CommandText = "INSERT INTO ServerMetrics (ServerName, MetricName, Value, Unit, Timestamp) VALUES (@server, @metric, @value, @unit, @ts)"
$cmd.Parameters.AddWithValue("@server", $ServerName) $cmd.Parameters.AddWithValue("@metric", $MetricName) $cmd.Parameters.AddWithValue("@value", $Value) $cmd.Parameters.AddWithValue("@unit", $Unit) $cmd.Parameters.AddWithValue("@ts", (Get-Date).ToString("yyyy-MM-dd HH:mm:ss"))
$cmd.ExecuteNonQuery() }
$servers = @("SRV01", "SRV02", "SRV03") $metrics = @( @{ Name = "CPUUsage"; Unit = "%" } @{ Name = "MemoryUsage"; Unit = "%" } @{ Name = "DiskFree"; Unit = "GB" } )
foreach ($server in $servers) { foreach ($metric in $metrics) { $value = switch ($metric.Name) { "CPUUsage" { Get-Random -Minimum 20 -Maximum 95 } "MemoryUsage" { Get-Random -Minimum 40 -Maximum 90 } "DiskFree" { [math]::Round((Get-Random -Minimum 50 -Maximum 500) / 1.0, 2) } } Add-Metric -Connection $conn -ServerName $server -MetricName $metric.Name -Value $value -Unit $metric.Unit } }
Write-Host "已插入测试数据" -ForegroundColor Green $conn.Close()
|