Files
DBAdmin/toolbox/DBAToolBox.ps1
T
2026-05-28 06:56:18 +00:00

85 lines
2.5 KiB
PowerShell

Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase
# Import Custom Modules
Import-Module (Join-Path $PSScriptRoot "Modules\SQLManager.psm1") -Force
# Configuration Paths
$configPath = Join-Path $PSScriptRoot "Config\settings.json"
# Load Settings
if (Test-Path $configPath) {
$settings = Get-Content $configPath | ConvertFrom-Json
} else {
$settings = [pscustomobject]@{ LastServer = ""; Theme = "Light" }
}
# 1. Path to XAML
$xamlFile = Join-Path $PSScriptRoot "UI\MainWindow.xaml"
# 2. Load XAML
[xml]$xml = Get-Content $xamlFile
$reader = New-Object System.Xml.XmlNodeReader($xml)
$Window = [Windows.Markup.XamlReader]::Load($reader)
# 3. Extract controls from XAML
$btnConnect = $Window.FindName("btnConnect")
$txtServerName = $Window.FindName("txtServerName")
$txtLogs = $Window.FindName("txtLogs")
$dgServerInfo = $Window.FindName("dgServerInfo")
# Set initial values from settings
$txtServerName.Text = $settings.LastServer
# 4. Helper function for logging
function Write-Log {
param([string]$Message)
$timestamp = Get-Date -Format "HH:mm:ss"
$txtLogs.Dispatcher.Invoke({
$txtLogs.AppendText("[$timestamp] $Message`r`n")
$txtLogs.ScrollToEnd()
})
}
# 5. Connection logic
$btnConnect.Add_Click({
$server = $txtServerName.Text
if ([string]::IsNullOrWhiteSpace($server)) {
Write-Log "Error: Please enter a server name."
return
}
$btnConnect.IsEnabled = $false
Write-Log "Attempting to connect to $server..."
# Save last server
$settings.LastServer = $server
$settings | ConvertTo-Json | Set-Content $configPath
try {
$result = Test-SQLConnection -ServerInstance $server
if ($result.Success) {
Write-Log "Connected successfully to $($result.Instance)!"
$dgServerInfo.ItemsSource = @($result) | Select-Object Instance, Version, Edition, Status
} else {
Write-Log "Connection failed: $($result.Error)"
}
} catch {
Write-Log "Critical Error: $($_.Exception.Message)"
} finally {
$btnConnect.IsEnabled = $true
}
})
# Startup Dependency Check
try {
Import-DBAToolBoxDependencies
Write-Log "DBAToolBox started. dbatools module loaded."
} catch {
[System.Windows.MessageBox]::Show($_.Exception.Message, "Dependency Error", "OK", "Error")
# In some environments ShowDialog might fail if no UI thread, but for WPF it should work.
$Window.Close()
}
# 6. Show Window
$Window.ShowDialog() | Out-Null