-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQL-Migration.ps1
More file actions
1525 lines (1365 loc) · 63.4 KB
/
SQL-Migration.ps1
File metadata and controls
1525 lines (1365 loc) · 63.4 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 5.1
# =============================================================================
# SQL-Migration.ps1
# Hauptskript mit WinForms-GUI fuer SQL Server Migrationen
#
# Betriebsmodi (Option C):
# - Beim Start: Rollenauswahl (Quelle / Ziel / Automatisch)
# - Automatisch: Zustandsdatei im Exchange-Pfad vorhanden -> Ziel-Modus
# sonst -> Quell-Modus
# - GUI zeigt nur die relevante Seite (Quelle ODER Ziel)
#
# Szenario-Erkennung (Option B):
# - Direct: Zielserver TCP-erreichbar -> versuche UNC direkt;
# bei Fehler automatisch lokal+Copy
# - TwoPhase: Zielserver nicht erreichbar -> nur Phase1 (Quelle)
# oder nur Phase2 (Ziel)
# =============================================================================
[CmdletBinding()]
param(
[string]$ConfigFile = "$PSScriptRoot\config\migration.config.json",
# Rollenvorgabe per Parameter moeglich (uebersteuert Dialog)
[ValidateSet('','Source','Target','Auto')]
[string]$Role = ''
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# ---------------------------------------------------------------------------
# Assemblies laden
# ---------------------------------------------------------------------------
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[System.Windows.Forms.Application]::EnableVisualStyles()
# ---------------------------------------------------------------------------
# Module laden
# ---------------------------------------------------------------------------
$modulePath = Join-Path $PSScriptRoot 'modules'
@(
'Write-MigrationLog',
'Connect-SqlServer',
'Get-SqlObjects',
'Invoke-MigrationState',
'Invoke-Migration'
) | ForEach-Object {
$mp = Join-Path $modulePath "$_.psm1"
if (Test-Path $mp) {
Import-Module $mp -Force -ErrorAction Stop
} else {
throw "Modul nicht gefunden: $mp"
}
}
# dbaTools pruefen
if (-not (Get-Module -ListAvailable -Name dbaTools)) {
[System.Windows.Forms.MessageBox]::Show(
"dbaTools ist nicht installiert.`nBitte installieren: Install-Module dbaTools",
'Fehlende Abhaengigkeit', 'OK', 'Error') | Out-Null
exit 1
}
Import-Module dbaTools -ErrorAction Stop
# ---------------------------------------------------------------------------
# Konfiguration laden
# ---------------------------------------------------------------------------
$Config = @{
DefaultExchangePath = "\\exchange-server\SQLMigration\Backups"
DefaultLocalBackupPath = "F:\Daten\SQL\Backup"
DefaultLogPath = "C:\SQLMigration\Logs"
LogFilePrefix = 'SQL-Migration'
ConnectionTimeout = 30
BackupCompression = $true
VerifyBackup = $true
CopyOnlyBackup = $true
DefaultMigrationMethod = 'BackupRestore'
UncAccessTestTimeoutSec = 10
StateFileName = '_migration_state.json'
TrustServerCertificate = $true
}
if (Test-Path $ConfigFile) {
try {
$jsonCfg = Get-Content $ConfigFile -Raw | ConvertFrom-Json
foreach ($prop in $jsonCfg.PSObject.Properties) {
$Config[$prop.Name] = $prop.Value
}
} catch { <# Defaults beibehalten #> }
}
# Logverzeichnis anlegen
if (-not (Test-Path $Config.DefaultLogPath)) {
New-Item -ItemType Directory -Path $Config.DefaultLogPath -Force | Out-Null
}
$null = Initialize-MigrationLog -LogDirectory $Config.DefaultLogPath `
-Prefix $Config.LogFilePrefix
# ---------------------------------------------------------------------------
# Globale Zustandsvariablen
# ---------------------------------------------------------------------------
$script:ActiveServer = $null # Verbundener Server (Quelle oder Ziel)
$script:ActiveAuth = 'Windows'
$script:ExchangePath = $Config.DefaultExchangePath
$script:LocalBackupPath= $Config.DefaultLocalBackupPath
$script:ActiveRole = '' # 'Source' | 'Target'
$script:Scenario = '' # 'Direct' | 'TwoPhase'
$script:LoadedState = $null # Zustandsdatei (im Ziel-Modus)
# ===========================================================================
# FARBEN & SCHRIFTEN
# ===========================================================================
$clrBg = [System.Drawing.Color]::FromArgb(24, 26, 32)
$clrPanel = [System.Drawing.Color]::FromArgb(33, 37, 43)
$clrBorder = [System.Drawing.Color]::FromArgb(52, 58, 70)
$clrAccent = [System.Drawing.Color]::FromArgb(0, 120, 215)
$clrAccentGrn = [System.Drawing.Color]::FromArgb(40, 167, 69)
$clrAccentAmb = [System.Drawing.Color]::FromArgb(255, 140, 0)
$clrText = [System.Drawing.Color]::FromArgb(220, 225, 235)
$clrSubText = [System.Drawing.Color]::FromArgb(140, 150, 165)
$clrInput = [System.Drawing.Color]::FromArgb(40, 44, 52)
$clrHeader = [System.Drawing.Color]::FromArgb(15, 17, 22)
$fntTitle = New-Object System.Drawing.Font('Consolas', 12, [System.Drawing.FontStyle]::Bold)
$fntNormal = New-Object System.Drawing.Font('Segoe UI', 9)
$fntBold = New-Object System.Drawing.Font('Segoe UI', 9, [System.Drawing.FontStyle]::Bold)
$fntSmall = New-Object System.Drawing.Font('Segoe UI', 8)
$fntMono = New-Object System.Drawing.Font('Consolas', 8)
# ===========================================================================
# HILFS-DIALOG: Rollenauswahl beim Start (Option C)
# ===========================================================================
function Show-RoleDialog {
param([string]$ExchangePath, [string]$StateFileName)
$stateFile = Join-Path $ExchangePath $StateFileName
$stateExists = Test-Path $stateFile
$dlg = New-Object System.Windows.Forms.Form
$dlg.Text = 'SQL Migration - Rollenauswahl'
$dlg.Size = New-Object System.Drawing.Size(480, 320)
$dlg.StartPosition= 'CenterScreen'
$dlg.BackColor = $clrBg
$dlg.ForeColor = $clrText
$dlg.Font = $fntNormal
$dlg.FormBorderStyle = 'FixedDialog'
$dlg.MaximizeBox = $false
$lbl = New-Object System.Windows.Forms.Label
$lbl.Text = 'Welche Rolle uebernimmt dieses Script auf diesem Rechner?'
$lbl.Font = $fntBold
$lbl.ForeColor = $clrText
$lbl.AutoSize = $false
$lbl.Size = New-Object System.Drawing.Size(440, 40)
$lbl.Location = New-Object System.Drawing.Point(16, 16)
$dlg.Controls.Add($lbl)
$lblState = New-Object System.Windows.Forms.Label
$lblState.Font = $fntSmall
$lblState.AutoSize = $false
$lblState.Size = New-Object System.Drawing.Size(440, 20)
$lblState.Location = New-Object System.Drawing.Point(16, 58)
if ($stateExists) {
$lblState.Text = '[OK] Zustandsdatei gefunden im Exchange-Pfad - Ziel-Modus empfohlen'
$lblState.ForeColor= [System.Drawing.Color]::FromArgb(40,167,69)
} else {
$lblState.Text = '[ ] Keine Zustandsdatei gefunden - Quell-Modus empfohlen'
$lblState.ForeColor= $clrSubText
}
$dlg.Controls.Add($lblState)
# -----------------------------------------------------------------------
# Buttons ohne Closures:
# - DialogResult = OK signalisiert dass ein Button gedrueckt wurde
# - Tag des Forms traegt den gewaehlten Wert
# -----------------------------------------------------------------------
$btnSource = New-Object System.Windows.Forms.Button
$btnSource.Size = New-Object System.Drawing.Size(430, 46)
$btnSource.Location = New-Object System.Drawing.Point(16, 88)
$btnSource.BackColor= [System.Drawing.Color]::FromArgb(40,44,52)
$btnSource.ForeColor= $clrText
$btnSource.FlatStyle= 'Flat'
$btnSource.FlatAppearance.BorderColor = $clrAccent
$btnSource.FlatAppearance.BorderSize = 2
$btnSource.Text = ">> QUELL-Server (Phase 1)`r`nBackup / Detach + Copy auf Exchange-Pfad. Zustandsdatei wird erstellt."
$btnSource.TextAlign= 'MiddleLeft'
$btnSource.Padding = New-Object System.Windows.Forms.Padding(10,0,0,0)
$btnSource.DialogResult = [System.Windows.Forms.DialogResult]::Yes # Yes = Source
$dlg.Controls.Add($btnSource)
$btnTarget = New-Object System.Windows.Forms.Button
$btnTarget.Size = New-Object System.Drawing.Size(430, 46)
$btnTarget.Location = New-Object System.Drawing.Point(16, 144)
$btnTarget.BackColor= [System.Drawing.Color]::FromArgb(40,44,52)
$btnTarget.ForeColor= $clrText
$btnTarget.FlatStyle= 'Flat'
$btnTarget.FlatAppearance.BorderColor = $clrAccentGrn
$btnTarget.FlatAppearance.BorderSize = 2
$btnTarget.Text = "<< ZIEL-Server (Phase 2)`r`nCopy vom Exchange-Pfad + Restore / Attach. Liest Zustandsdatei."
$btnTarget.TextAlign= 'MiddleLeft'
$btnTarget.Padding = New-Object System.Windows.Forms.Padding(10,0,0,0)
$btnTarget.DialogResult = [System.Windows.Forms.DialogResult]::No # No = Target
$dlg.Controls.Add($btnTarget)
$btnAuto = New-Object System.Windows.Forms.Button
$btnAuto.Size = New-Object System.Drawing.Size(430, 46)
$btnAuto.Location = New-Object System.Drawing.Point(16, 200)
$btnAuto.BackColor= [System.Drawing.Color]::FromArgb(40,44,52)
$btnAuto.ForeColor= $clrText
$btnAuto.FlatStyle= 'Flat'
$btnAuto.FlatAppearance.BorderColor = $clrAccentAmb
$btnAuto.FlatAppearance.BorderSize = 2
$btnAuto.Text = "** AUTOMATISCH erkennen`r`nZustandsdatei vorhanden -> Ziel; sonst -> Quelle."
$btnAuto.TextAlign= 'MiddleLeft'
$btnAuto.Padding = New-Object System.Windows.Forms.Padding(10,0,0,0)
$btnAuto.DialogResult = [System.Windows.Forms.DialogResult]::Retry # Retry = Auto
$dlg.Controls.Add($btnAuto)
$dr = $dlg.ShowDialog()
$dlg.Dispose()
switch ($dr) {
([System.Windows.Forms.DialogResult]::Yes) { return 'Source' }
([System.Windows.Forms.DialogResult]::No) { return 'Target' }
([System.Windows.Forms.DialogResult]::Retry) { return 'Auto' }
default { return '' }
}
}
# ===========================================================================
# STATUSLEISTE (thread-safe)
# ===========================================================================
function Update-StatusBar {
param([string]$Text, [string]$Color = 'Info')
$c = switch ($Color) {
'Error' { [System.Drawing.Color]::FromArgb(220,53,69) }
'Success' { [System.Drawing.Color]::FromArgb(40,167,69) }
'Warn' { [System.Drawing.Color]::FromArgb(255,193,7) }
default { [System.Drawing.Color]::FromArgb(23,162,184) }
}
if ($script:statusLabel -and $script:statusLabel.IsHandleCreated) {
$script:statusLabel.Invoke([Action]{
$script:statusLabel.Text = $Text
$script:statusLabel.BackColor = $c
})
}
}
# ===========================================================================
# HILFS: Scrollbarer Fehler-Dialog (zeigt komplette Exception-Kette)
# ===========================================================================
function Show-ErrorDialog {
param(
[string]$Title = 'Fehler',
[string]$Message
)
$dlgErr = New-Object System.Windows.Forms.Form
$dlgErr.Text = $Title
$dlgErr.Size = New-Object System.Drawing.Size(700, 450)
$dlgErr.StartPosition= 'CenterScreen'
$dlgErr.BackColor = $clrBg
$dlgErr.ForeColor = $clrText
$dlgErr.Font = $fntSmall
$dlgErr.FormBorderStyle = 'Sizable'
$lblErrHint = New-Object System.Windows.Forms.Label
$lblErrHint.Text = 'Vollstaendige Fehlermeldung (kann kopiert werden):'
$lblErrHint.Font = $fntBold
$lblErrHint.ForeColor= [System.Drawing.Color]::FromArgb(220,53,69)
$lblErrHint.AutoSize = $true
$lblErrHint.Location = New-Object System.Drawing.Point(10, 10)
$dlgErr.Controls.Add($lblErrHint)
$txtErr = New-Object System.Windows.Forms.TextBox
$txtErr.Multiline = $true
$txtErr.ScrollBars = 'Both'
$txtErr.ReadOnly = $true
$txtErr.WordWrap = $false
$txtErr.Font = $fntMono
$txtErr.BackColor = $clrInput
$txtErr.ForeColor = [System.Drawing.Color]::FromArgb(255,120,120)
$txtErr.BorderStyle = 'None'
$txtErr.Text = $Message
$txtErr.Size = New-Object System.Drawing.Size(670, 340)
$txtErr.Location = New-Object System.Drawing.Point(10, 35)
$dlgErr.Controls.Add($txtErr)
$btnClose = New-Object System.Windows.Forms.Button
$btnClose.Text = 'Schliessen'
$btnClose.Font = $fntBold
$btnClose.Size = New-Object System.Drawing.Size(120, 28)
$btnClose.Location = New-Object System.Drawing.Point(10, 385)
$btnClose.BackColor = [System.Drawing.Color]::FromArgb(60,63,70)
$btnClose.ForeColor = $clrText
$btnClose.FlatStyle = 'Flat'
$btnClose.FlatAppearance.BorderSize = 0
$btnClose.DialogResult = [System.Windows.Forms.DialogResult]::OK
$dlgErr.Controls.Add($btnClose)
$dlgErr.ShowDialog() | Out-Null
$dlgErr.Dispose()
}
# Hilfsfunktion: vollstaendige Exception-Kette als Text
function Get-ExceptionDetail {
param([System.Exception]$Ex)
$lines = [System.Collections.Generic.List[string]]::new()
$depth = 0
$current = $Ex
while ($current -ne $null) {
$indent = ' ' * $depth
$lines.Add("${indent}[$($current.GetType().Name)]")
$lines.Add("${indent}$($current.Message)")
if ($current.StackTrace) {
$st = ($current.StackTrace -split "`n") | Select-Object -First 5
foreach ($line in $st) {
$lines.Add("${indent} $($line.Trim())")
}
}
$lines.Add('')
$current = $current.InnerException
$depth++
}
return $lines -join "`r`n"
}
# ===========================================================================
# HILFS: ListView befuellen
# ===========================================================================
function Set-ListViewData {
param(
[System.Windows.Forms.ListView]$ListView,
[object[]]$Data,
[string[]]$Properties
)
$ListView.BeginUpdate()
$ListView.Items.Clear()
if ($Data) {
foreach ($row in $Data) {
$vals = $Properties | ForEach-Object {
$v = $row.$_; if ($null -eq $v) { '' } else { $v.ToString() }
}
$item = New-Object System.Windows.Forms.ListViewItem($vals[0])
$item.Checked = $true # standardmaessig alle markiert
for ($i = 1; $i -lt $vals.Count; $i++) {
$null = $item.SubItems.Add($vals[$i])
}
$ListView.Items.Add($item) | Out-Null
}
}
$ListView.EndUpdate()
# Zaehler-Label aktualisieren (Tag = Label-Referenz)
if ($ListView.Tag -and $ListView.Tag -is [System.Windows.Forms.Label]) {
$ListView.Tag.Text = "$($ListView.CheckedItems.Count) / $($ListView.Items.Count) ausgewaehlt"
}
}
# ===========================================================================
# HINTERGRUND-JOB (Runspace, GUI friert nicht ein)
# ===========================================================================
# Job-Kontexte: Hashtable mit eindeutigem Schluessel pro Job.
# Benoetigt weil PS 5.1 ISE lokale Variablen in Timer-Add_Tick-Handlern
# nicht zuverlaessig bereitstellt. $script:-Scope ist immer erreichbar.
$script:_JobContexts = @{}
$script:_JobCounter = 0
function Invoke-BackgroundJob {
param(
[Parameter(Mandatory)][scriptblock]$ScriptBlock,
[object[]]$ArgumentList = @(),
[System.Action[object]]$OnComplete,
[System.Action[string]]$OnError
)
# Eindeutiger Schluessel fuer diesen Job
$script:_JobCounter++
$jobKey = "Job_$($script:_JobCounter)"
$pool = [runspacefactory]::CreateRunspacePool(1, 1)
$pool.ApartmentState = 'STA'
$pool.Open()
$ps = [powershell]::Create()
$ps.RunspacePool = $pool
$initScript = [scriptblock]::Create(@"
Set-StrictMode -Off
`$ErrorActionPreference = 'Continue'
Import-Module dbaTools -ErrorAction SilentlyContinue
Import-Module '$modulePath\Write-MigrationLog.psm1' -Force
Import-Module '$modulePath\Connect-SqlServer.psm1' -Force
Import-Module '$modulePath\Get-SqlObjects.psm1' -Force
Import-Module '$modulePath\Invoke-MigrationState.psm1' -Force
Import-Module '$modulePath\Invoke-Migration.psm1' -Force
"@)
$null = $ps.AddScript($initScript).Invoke()
$ps.Commands.Clear()
$null = $ps.AddScript($ScriptBlock)
foreach ($a in $ArgumentList) { $null = $ps.AddArgument($a) }
$handle = $ps.BeginInvoke()
# Kontext im script:-Scope speichern - vom Timer-Handler abrufbar
$script:_JobContexts[$jobKey] = @{
Ps = $ps
Pool = $pool
Handle = $handle
OnComplete = $OnComplete
OnError = $OnError
}
$timer = New-Object System.Windows.Forms.Timer
$timer.Interval = 250
$timer.Tag = $jobKey # Schluessel am Timer-Objekt selbst speichern
$timer.Add_Tick({
# $this = der Timer der gerade feuert (PS 5.1 stellt $this in Event-Handlern bereit)
$key = $this.Tag
$ctx = $script:_JobContexts[$key]
if (-not $ctx) { $this.Stop(); $this.Dispose(); return }
if ($ctx.Handle.IsCompleted) {
$this.Stop()
$this.Dispose()
$script:_JobContexts.Remove($key)
try {
$result = $ctx.Ps.EndInvoke($ctx.Handle)
# Streams.Error zusaetzlich pruefen (non-terminating errors)
$streamErrors = @($ctx.Ps.Streams.Error)
if ($ctx.Ps.HadErrors -and $streamErrors.Count -gt 0) {
$lines = [System.Collections.Generic.List[string]]::new()
foreach ($se in $streamErrors) {
$lines.Add($se.ToString())
if ($se.Exception -and $se.Exception.InnerException) {
$lines.Add(' Inner: ' + $se.Exception.InnerException.Message)
}
}
$errMsg = $lines -join "`r`n"
if ($ctx.OnError) { $ctx.OnError.Invoke($errMsg) }
} else {
if ($ctx.OnComplete) { $ctx.OnComplete.Invoke($result) }
}
} catch {
# EndInvoke wirft bei terminating errors im Runspace
$detail = Get-ExceptionDetail -Ex $_.Exception
# Streams nochmals pruefen fuer zusaetzlichen Kontext
try {
$streamDetail = $ctx.Ps.Streams.Error |
ForEach-Object { $_.ToString() } | Out-String
if ($streamDetail.Trim()) {
$detail = "=== Runspace Streams.Error ===`r`n$streamDetail`r`n`r`n=== Exception ===`r`n$detail"
}
} catch { }
if ($ctx.OnError) { $ctx.OnError.Invoke($detail) }
} finally {
try { $ctx.Ps.Dispose() } catch { }
try { $ctx.Pool.Close() } catch { }
try { $ctx.Pool.Dispose()} catch { }
}
}
})
$timer.Start()
}
# ===========================================================================
# ROLLENAUSWAHL
# ===========================================================================
$chosenRole = $Role
if (-not $chosenRole -or $chosenRole -eq 'Auto') {
if (-not $chosenRole) {
# Exchange-Pfad fuer Dialog brauchen wir schon hier
$tmpExPath = $Config.DefaultExchangePath
$chosenRole = Show-RoleDialog -ExchangePath $tmpExPath `
-StateFileName $Config.StateFileName
if (-not $chosenRole) { exit 0 } # Abbruch
}
if ($chosenRole -eq 'Auto') {
$stateFile = Join-Path $Config.DefaultExchangePath $Config.StateFileName
$chosenRole = if (Test-Path $stateFile) { 'Target' } else { 'Source' }
Write-MigrationLog -Level 'INFO' -Category 'ROLE' `
-Message "Automatische Rolle: $chosenRole"
}
}
$script:ActiveRole = $chosenRole
# Im Ziel-Modus: Zustandsdatei laden
if ($script:ActiveRole -eq 'Target') {
$script:LoadedState = Read-MigrationState `
-ExchangePath $Config.DefaultExchangePath `
-StateFileName $Config.StateFileName
}
# ===========================================================================
# HAUPTFENSTER
# ===========================================================================
$roleLabel = if ($script:ActiveRole -eq 'Source') { 'QUELL-SERVER' } else { 'ZIEL-SERVER' }
$roleColor = if ($script:ActiveRole -eq 'Source') { $clrAccent } else { $clrAccentGrn }
$form = New-Object System.Windows.Forms.Form
$form.Text = "SQL Server Migration Tool v1.1 - $roleLabel"
$form.Size = New-Object System.Drawing.Size(900, 900)
$form.MinimumSize = New-Object System.Drawing.Size(700, 700)
$form.StartPosition = 'CenterScreen'
$form.BackColor = $clrBg
$form.ForeColor = $clrText
$form.Font = $fntNormal
# ---------------------------------------------------------------------------
# TITELLEISTE
# ---------------------------------------------------------------------------
$pnlTitle = New-Object System.Windows.Forms.Panel
$pnlTitle.Dock = 'Top'
$pnlTitle.Height = 50
$pnlTitle.BackColor = $clrHeader
$form.Controls.Add($pnlTitle)
$lblTitle = New-Object System.Windows.Forms.Label
$lblTitle.Text = ">> SQL SERVER MIGRATION - $roleLabel"
$lblTitle.Font = $fntTitle
$lblTitle.ForeColor = $roleColor
$lblTitle.AutoSize = $true
$lblTitle.Location = New-Object System.Drawing.Point(15, 13)
$pnlTitle.Controls.Add($lblTitle)
$lblVersion = New-Object System.Windows.Forms.Label
$lblVersion.Text = 'PS ' + $PSVersionTable.PSVersion.ToString() + ' | dbaTools'
$lblVersion.Font = $fntSmall
$lblVersion.ForeColor = $clrSubText
$lblVersion.AutoSize = $true
$lblVersion.Location = New-Object System.Drawing.Point(560, 17)
$pnlTitle.Controls.Add($lblVersion)
$lblLogPath = New-Object System.Windows.Forms.Label
$lblLogPath.Font = $fntSmall
$lblLogPath.ForeColor = $clrSubText
$lblLogPath.AutoSize = $false
$lblLogPath.TextAlign = 'MiddleRight'
$lblLogPath.Size = New-Object System.Drawing.Size(300, 20)
$lblLogPath.Location = New-Object System.Drawing.Point(570, 15)
$lblLogPath.Text = 'Log: ' + (Get-MigrationLogPath)
$pnlTitle.Controls.Add($lblLogPath)
# ---------------------------------------------------------------------------
# STATUSLEISTE
# ---------------------------------------------------------------------------
$pnlStatus = New-Object System.Windows.Forms.Panel
$pnlStatus.Dock = 'Bottom'
$pnlStatus.Height = 28
$pnlStatus.BackColor = $clrHeader
$form.Controls.Add($pnlStatus)
$script:statusLabel = New-Object System.Windows.Forms.Label
$script:statusLabel.Dock = 'Fill'
$script:statusLabel.Font = $fntSmall
$script:statusLabel.ForeColor= $clrText
$script:statusLabel.BackColor= [System.Drawing.Color]::FromArgb(23,162,184)
$script:statusLabel.TextAlign= 'MiddleLeft'
$script:statusLabel.Padding = New-Object System.Windows.Forms.Padding(10,0,0,0)
$script:statusLabel.Text = " Bereit. Bitte $roleLabel verbinden."
$pnlStatus.Controls.Add($script:statusLabel)
# ---------------------------------------------------------------------------
# HAUPT-PANEL (einspaltig - nur eine Rolle)
# ---------------------------------------------------------------------------
$pnlMain = New-Object System.Windows.Forms.Panel
$pnlMain.Dock = 'Fill'
$pnlMain.BackColor = $clrBg
$form.Controls.Add($pnlMain)
$form.Controls.SetChildIndex($pnlMain, 0)
# --- Kopfzeile Server-Panel ---
$pnlHead = New-Object System.Windows.Forms.Panel
$pnlHead.Dock = 'Top'
$pnlHead.Height = 32
$pnlHead.BackColor = $clrHeader
$pnlMain.Controls.Add($pnlHead)
$lblCaption = New-Object System.Windows.Forms.Label
$lblCaption.Text = $roleLabel
$lblCaption.Font = $fntBold
$lblCaption.ForeColor = $roleColor
$lblCaption.AutoSize = $true
$lblCaption.Location = New-Object System.Drawing.Point(10,7)
$pnlHead.Controls.Add($lblCaption)
$lblConnState = New-Object System.Windows.Forms.Label
$lblConnState.Text = '* Nicht verbunden'
$lblConnState.Font = $fntSmall
$lblConnState.ForeColor = [System.Drawing.Color]::FromArgb(220,53,69)
$lblConnState.AutoSize = $true
$lblConnState.Location = New-Object System.Drawing.Point(160,9)
$pnlHead.Controls.Add($lblConnState)
# --- Verbindungs-Panel ---
$pnlConn = New-Object System.Windows.Forms.Panel
$pnlConn.Dock = 'Top'
$pnlConn.Height = 115
$pnlConn.BackColor = $clrPanel
$pnlConn.Padding = New-Object System.Windows.Forms.Padding(8,6,8,6)
$pnlMain.Controls.Add($pnlConn)
$lblSrv = New-Object System.Windows.Forms.Label
$lblSrv.Text = 'Server\Instanz:'
$lblSrv.Font = $fntSmall
$lblSrv.ForeColor = $clrSubText
$lblSrv.AutoSize = $true
$lblSrv.Location = New-Object System.Drawing.Point(8, 10)
$pnlConn.Controls.Add($lblSrv)
$txtServer = New-Object System.Windows.Forms.TextBox
$txtServer.Font = $fntMono
$txtServer.BackColor= $clrInput
$txtServer.ForeColor= $clrText
$txtServer.BorderStyle = 'FixedSingle'
$txtServer.Size = New-Object System.Drawing.Size(250, 22)
$txtServer.Location = New-Object System.Drawing.Point(115, 7)
# Im Ziel-Modus: Zielserver aus Zustandsdatei vorbelegen
if ($script:ActiveRole -eq 'Target' -and $script:LoadedState) {
$txtServer.Text = $script:LoadedState.TargetServer
}
$pnlConn.Controls.Add($txtServer)
$lblAuth = New-Object System.Windows.Forms.Label
$lblAuth.Text = 'Auth:'
$lblAuth.Font = $fntSmall
$lblAuth.ForeColor = $clrSubText
$lblAuth.AutoSize = $true
$lblAuth.Location = New-Object System.Drawing.Point(380, 10)
$pnlConn.Controls.Add($lblAuth)
$cmbAuth = New-Object System.Windows.Forms.ComboBox
$cmbAuth.Font = $fntSmall
$cmbAuth.BackColor = $clrInput
$cmbAuth.ForeColor = $clrText
$cmbAuth.FlatStyle = 'Flat'
$cmbAuth.DropDownStyle = 'DropDownList'
$cmbAuth.Size = New-Object System.Drawing.Size(110, 22)
$cmbAuth.Location = New-Object System.Drawing.Point(415, 7)
$cmbAuth.Items.AddRange(@('Windows', 'SQL-Login')) | Out-Null
$cmbAuth.SelectedIndex = 0
$pnlConn.Controls.Add($cmbAuth)
$lblUser = New-Object System.Windows.Forms.Label
$lblUser.Text = 'Benutzer:'; $lblUser.Font = $fntSmall
$lblUser.ForeColor = $clrSubText; $lblUser.AutoSize = $true
$lblUser.Location = New-Object System.Drawing.Point(8, 40); $lblUser.Visible = $false
$pnlConn.Controls.Add($lblUser)
$txtUser = New-Object System.Windows.Forms.TextBox
$txtUser.Font = $fntMono; $txtUser.BackColor = $clrInput; $txtUser.ForeColor = $clrText
$txtUser.BorderStyle = 'FixedSingle'; $txtUser.Size = New-Object System.Drawing.Size(140, 22)
$txtUser.Location = New-Object System.Drawing.Point(75, 37); $txtUser.Visible = $false
$pnlConn.Controls.Add($txtUser)
$lblPwd = New-Object System.Windows.Forms.Label
$lblPwd.Text = 'Passwort:'; $lblPwd.Font = $fntSmall
$lblPwd.ForeColor = $clrSubText; $lblPwd.AutoSize = $true
$lblPwd.Location = New-Object System.Drawing.Point(230, 40); $lblPwd.Visible = $false
$pnlConn.Controls.Add($lblPwd)
$txtPwd = New-Object System.Windows.Forms.TextBox
$txtPwd.Font = $fntMono; $txtPwd.BackColor = $clrInput; $txtPwd.ForeColor = $clrText
$txtPwd.BorderStyle = 'FixedSingle'; $txtPwd.PasswordChar = '*'
$txtPwd.Size = New-Object System.Drawing.Size(140, 22)
$txtPwd.Location = New-Object System.Drawing.Point(295, 37); $txtPwd.Visible = $false
$pnlConn.Controls.Add($txtPwd)
$cmbAuth.Add_SelectedIndexChanged({
$isSql = ($cmbAuth.SelectedItem -eq 'SQL-Login')
$lblUser.Visible = $isSql; $txtUser.Visible = $isSql
$lblPwd.Visible = $isSql; $txtPwd.Visible = $isSql
$pnlConn.Height = if ($isSql) { 155 } else { 140 }
})
$chkTrust = New-Object System.Windows.Forms.CheckBox
$chkTrust.Text = 'TrustServerCertificate (SQL 2022 / selbstsigniertes Zertifikat)'
$chkTrust.Font = $fntSmall
$chkTrust.ForeColor= [System.Drawing.Color]::FromArgb(255,193,7)
$chkTrust.AutoSize = $true
$chkTrust.Checked = [bool]$Config.TrustServerCertificate
$chkTrust.Location = New-Object System.Drawing.Point(8, 75)
$pnlConn.Controls.Add($chkTrust)
$btnConnect = New-Object System.Windows.Forms.Button
$btnConnect.Text = 'Verbinden'; $btnConnect.Font = $fntBold
$btnConnect.Size = New-Object System.Drawing.Size(90, 26)
$btnConnect.Location = New-Object System.Drawing.Point(8, 100)
$btnConnect.BackColor = $roleColor; $btnConnect.ForeColor = [System.Drawing.Color]::White
$btnConnect.FlatStyle = 'Flat'; $btnConnect.FlatAppearance.BorderSize = 0
$pnlConn.Controls.Add($btnConnect)
$btnDisconnect = New-Object System.Windows.Forms.Button
$btnDisconnect.Text = 'Trennen'; $btnDisconnect.Font = $fntSmall
$btnDisconnect.Size = New-Object System.Drawing.Size(70, 26)
$btnDisconnect.Location = New-Object System.Drawing.Point(108, 100)
$btnDisconnect.BackColor = [System.Drawing.Color]::FromArgb(60,63,70)
$btnDisconnect.ForeColor = $clrText; $btnDisconnect.FlatStyle = 'Flat'
$btnDisconnect.FlatAppearance.BorderSize = 0; $btnDisconnect.Enabled = $false
$pnlConn.Controls.Add($btnDisconnect)
$lblInfo = New-Object System.Windows.Forms.Label
$lblInfo.Font = $fntSmall; $lblInfo.ForeColor = $clrSubText
$lblInfo.AutoSize = $false; $lblInfo.Size = New-Object System.Drawing.Size(350, 18)
$lblInfo.Location = New-Object System.Drawing.Point(190, 107)
$pnlConn.Controls.Add($lblInfo)
# pnlConn Standardhoehe anpassen
$pnlConn.Height = 140
# --- Globale Auswahl-Leiste (alle Tabs) ---
$pnlGlobalSel = New-Object System.Windows.Forms.Panel
$pnlGlobalSel.Dock = 'Top'
$pnlGlobalSel.Height = 28
$pnlGlobalSel.BackColor = $clrHeader
$pnlMain.Controls.Add($pnlGlobalSel)
$lblGlobal = New-Object System.Windows.Forms.Label
$lblGlobal.Text = 'Alle Tabs:'
$lblGlobal.Font = $fntSmall
$lblGlobal.ForeColor = $clrSubText
$lblGlobal.AutoSize = $true
$lblGlobal.Location = New-Object System.Drawing.Point(6, 7)
$pnlGlobalSel.Controls.Add($lblGlobal)
$btnGlobalAll = New-Object System.Windows.Forms.Button
$btnGlobalAll.Text = 'Alle markieren'
$btnGlobalAll.Font = $fntSmall
$btnGlobalAll.Size = New-Object System.Drawing.Size(110, 22)
$btnGlobalAll.Location = New-Object System.Drawing.Point(68, 3)
$btnGlobalAll.BackColor = [System.Drawing.Color]::FromArgb(40,167,69)
$btnGlobalAll.ForeColor = [System.Drawing.Color]::White
$btnGlobalAll.FlatStyle = 'Flat'
$btnGlobalAll.FlatAppearance.BorderSize = 0
$pnlGlobalSel.Controls.Add($btnGlobalAll)
$btnGlobalNone = New-Object System.Windows.Forms.Button
$btnGlobalNone.Text = 'Alle abwaehlen'
$btnGlobalNone.Font = $fntSmall
$btnGlobalNone.Size = New-Object System.Drawing.Size(110, 22)
$btnGlobalNone.Location = New-Object System.Drawing.Point(182, 3)
$btnGlobalNone.BackColor= [System.Drawing.Color]::FromArgb(108,117,125)
$btnGlobalNone.ForeColor= [System.Drawing.Color]::White
$btnGlobalNone.FlatStyle= 'Flat'
$btnGlobalNone.FlatAppearance.BorderSize = 0
$pnlGlobalSel.Controls.Add($btnGlobalNone)
# Globale Buttons: $script:_AllListViews wird nach Tab-Erstellung gesetzt
$btnGlobalAll.Add_Click({
foreach ($lv_ in $script:_AllListViews) {
$lv_.BeginUpdate()
foreach ($item in $lv_.Items) { $item.Checked = $true }
$lv_.EndUpdate()
}
})
$btnGlobalNone.Add_Click({
foreach ($lv_ in $script:_AllListViews) {
$lv_.BeginUpdate()
foreach ($item in $lv_.Items) { $item.Checked = $false }
$lv_.EndUpdate()
}
})
# --- Tab-Control ---
$tabs = New-Object System.Windows.Forms.TabControl
$tabs.Dock = 'Fill'
$tabs.BackColor = $clrBg
$tabs.Font = $fntSmall
$pnlMain.Controls.Add($tabs)
# WinForms Dock-Reihenfolge: Fill muss Index 0 sein.
# Top-Controls danach in umgekehrter visueller Reihenfolge
# (zuletzt eingefuegtes Top-Control erscheint oben).
# Gewuenschte visuelle Reihenfolge von oben nach unten:
# pnlHead (Servertitel)
# pnlConn (Verbindung)
# pnlGlobalSel (Alle/Keine)
# tabs (Fill - Rest)
$pnlMain.Controls.SetChildIndex($tabs, 0) # Fill: immer Index 0
$pnlMain.Controls.SetChildIndex($pnlGlobalSel, 1) # unterste Top-Leiste
$pnlMain.Controls.SetChildIndex($pnlConn, 2) # darueber
$pnlMain.Controls.SetChildIndex($pnlHead, 3) # ganz oben
function New-ObjectTab {
param([string]$Title, [string[][]]$Columns)
$tp = New-Object System.Windows.Forms.TabPage
$tp.Text = $Title; $tp.BackColor = $clrBg; $tp.ForeColor = $clrText
$tp.Padding = New-Object System.Windows.Forms.Padding(0)
# --- Button-Leiste oben im Tab ---
$pnlBtn = New-Object System.Windows.Forms.Panel
$pnlBtn.Dock = 'Top'
$pnlBtn.Height = 26
$pnlBtn.BackColor = $clrHeader
$btnAll = New-Object System.Windows.Forms.Button
$btnAll.Text = 'Alle'
$btnAll.Font = $fntSmall
$btnAll.Size = New-Object System.Drawing.Size(55, 22)
$btnAll.Location = New-Object System.Drawing.Point(2, 2)
$btnAll.BackColor = [System.Drawing.Color]::FromArgb(40,167,69)
$btnAll.ForeColor = [System.Drawing.Color]::White
$btnAll.FlatStyle = 'Flat'
$btnAll.FlatAppearance.BorderSize = 0
$pnlBtn.Controls.Add($btnAll)
$btnNone = New-Object System.Windows.Forms.Button
$btnNone.Text = 'Keine'
$btnNone.Font = $fntSmall
$btnNone.Size = New-Object System.Drawing.Size(55, 22)
$btnNone.Location = New-Object System.Drawing.Point(60, 2)
$btnNone.BackColor = [System.Drawing.Color]::FromArgb(108,117,125)
$btnNone.ForeColor = [System.Drawing.Color]::White
$btnNone.FlatStyle = 'Flat'
$btnNone.FlatAppearance.BorderSize = 0
$pnlBtn.Controls.Add($btnNone)
$lblCount = New-Object System.Windows.Forms.Label
$lblCount.Text = ''
$lblCount.Font = $fntSmall
$lblCount.ForeColor= $clrSubText
$lblCount.AutoSize = $true
$lblCount.Location = New-Object System.Drawing.Point(120, 5)
$pnlBtn.Controls.Add($lblCount)
$tp.Controls.Add($pnlBtn)
# --- ListView ---
$lv = New-Object System.Windows.Forms.ListView
$lv.Dock = 'Fill'; $lv.View = 'Details'; $lv.FullRowSelect = $true
$lv.GridLines = $true; $lv.CheckBoxes = $true
$lv.BackColor = $clrInput; $lv.ForeColor = $clrText
$lv.BorderStyle = 'None'; $lv.Font = $fntSmall; $lv.MultiSelect = $true
foreach ($col in $Columns) {
$c = New-Object System.Windows.Forms.ColumnHeader
$c.Text = $col[0]; $c.Width = [int]$col[1]
$lv.Columns.Add($c) | Out-Null
}
# Tag = ListView-Referenz fuer Event-Handler (kein Closure noetig)
$btnAll.Tag = $lv
$btnNone.Tag = $lv
$btnAll.Add_Click({
$lv_ = $this.Tag
$lv_.BeginUpdate()
foreach ($item in $lv_.Items) { $item.Checked = $true }
$lv_.EndUpdate()
})
$btnNone.Add_Click({
$lv_ = $this.Tag
$lv_.BeginUpdate()
foreach ($item in $lv_.Items) { $item.Checked = $false }
$lv_.EndUpdate()
})
# Zaehler aktualisieren wenn Checked-Status sich aendert
$lv.Tag = $lblCount
$lv.Add_ItemChecked({
$lbl_ = $this.Tag
if ($lbl_) {
$checked_ = ($this.CheckedItems.Count)
$total_ = ($this.Items.Count)
$lbl_.Text = "$checked_ / $total_ ausgewaehlt"
}
})
$tp.Controls.Add($lv)
$tabs.TabPages.Add($tp)
return $lv
}
$lvDbs = New-ObjectTab 'Datenbanken' @(
@('Name','160'),@('Status','70'),@('RecoveryModel','80'),
@('SizeGB','65'),@('Compatibility','90'),@('Owner','110'))
$lvLogins = New-ObjectTab 'Logins' @(
@('Name','180'),@('Typ','90'),@('Disabled','60'),
@('Locked','55'),@('System','55'),@('Erstellt','120'))
$lvUsers = New-ObjectTab 'DB-User' @(
@('Datenbank','140'),@('User','140'),@('LoginTyp','90'),
@('Login','130'),@('System','55'))
$lvLS = New-ObjectTab 'Linked Server' @(
@('Name','160'),@('Provider','110'),@('DataSource','160'),@('Product','100'))
$lvJobs = New-ObjectTab 'Agent Jobs' @(
@('Name','200'),@('Kategorie','110'),@('Owner','110'),
@('Aktiv','50'),@('LetzterLauf','130'))
$lvCreds = New-ObjectTab 'Credentials' @(
@('Name','160'),@('Identity','160'),@('Erstellt','120'))
$lvProx = New-ObjectTab 'Proxies' @(
@('Name','160'),@('Credential','140'),@('Aktiv','50'),@('Beschreibung','200'))
# Liste aller ListViews fuer globale Alle/Keine Buttons
$script:_AllListViews = @($lvDbs,$lvLogins,$lvUsers,$lvLS,$lvJobs,$lvCreds,$lvProx)
# ===========================================================================
# VERBINDEN-LOGIK
# ===========================================================================
$btnConnect.Add_Click({
# Alle Werte sofort in $script: sichern - lokale Variablen sind
# in OnComplete/OnError Callbacks nicht verfuegbar (PS 5.1 ISE)
$script:_ConnSrvName = $txtServer.Text.Trim()
$script:_ConnAuthMode = $cmbAuth.SelectedItem
$script:_ConnSqlUser = $txtUser.Text.Trim()
$script:_ConnTrust = $chkTrust.Checked
$script:_ConnTimeout = $Config.ConnectionTimeout
$script:_ConnPwdSS = if ($txtPwd.Text) {
$ss = New-Object System.Security.SecureString
$txtPwd.Text.ToCharArray() | ForEach-Object { $ss.AppendChar($_) }; $ss
} else { $null }
if (-not $script:_ConnSrvName) {
[System.Windows.Forms.MessageBox]::Show(
'Bitte Servernamen eingeben.','Hinweis','OK','Warning') | Out-Null
return
}
$btnConnect.Enabled = $false; $btnConnect.Text = '...'
$lblConnState.Text = '* Verbinde...'
$lblConnState.ForeColor = [System.Drawing.Color]::FromArgb(255,193,7)
Update-StatusBar "Verbinde mit $($script:_ConnSrvName) ..."
Invoke-BackgroundJob -ScriptBlock {
param($srv, $auth, $user, $pwdSS, $timeout, $trust)
$p = @{ ServerInstance=$srv; AuthMode=$auth; ConnectTimeout=$timeout
TrustServerCertificate=$trust }
if ($auth -eq 'SQL-Login') { $p['SqlUser']=$user; $p['SqlPassword']=$pwdSS }
New-SqlConnection @p
} -ArgumentList @(
$script:_ConnSrvName, $script:_ConnAuthMode, $script:_ConnSqlUser,
$script:_ConnPwdSS, $script:_ConnTimeout, $script:_ConnTrust
) `
-OnComplete {
param($result)
$conn = if ($result -is [array]) { $result[0] } else { $result }
$script:ActiveServer = $conn
$script:ActiveAuth = $script:_ConnAuthMode
$lblInfo.Invoke([Action]{ $lblInfo.Text = $conn.VersionString })
$lblConnState.Invoke([Action]{
$lblConnState.Text = "* Verbunden: $($script:_ConnSrvName)"
$lblConnState.ForeColor= [System.Drawing.Color]::FromArgb(40,167,69)
})
$btnConnect.Invoke([Action]{
$btnConnect.Enabled = $true; $btnConnect.Text = 'Neu laden'
})
$btnDisconnect.Invoke([Action]{ $btnDisconnect.Enabled = $true })
Update-StatusBar "Verbunden mit $($script:_ConnSrvName). Lade Objekte..." 'Info'
$dbs = Get-SqlDatabases -Server $conn -ExcludeSystem
$logins = Get-SqlLogins -Server $conn
$users = Get-SqlDbUsers -Server $conn
$ls = Get-SqlLinkedServers -Server $conn
$jobs = Get-SqlAgentJobs -Server $conn
$creds = Get-SqlCredentials -Server $conn
$prox = Get-SqlProxies -Server $conn
$lvDbs.Invoke([Action]{
Set-ListViewData $lvDbs $dbs @('Name','Status','RecoveryModel','SizeGB','Compatibility','Owner')
})
$lvLogins.Invoke([Action]{
Set-ListViewData $lvLogins $logins @('Name','LoginType','IsDisabled','IsLocked','IsSystem','CreateDate')
})
$lvUsers.Invoke([Action]{
Set-ListViewData $lvUsers $users @('Database','Name','LoginType','Login','IsSystemObject')
})
$lvLS.Invoke([Action]{
Set-ListViewData $lvLS $ls @('Name','ProviderName','DataSource','ProductName')
})
$lvJobs.Invoke([Action]{
Set-ListViewData $lvJobs $jobs @('Name','Category','OwnerLoginName','IsEnabled','LastRunDate')
})
$lvCreds.Invoke([Action]{
Set-ListViewData $lvCreds $creds @('Name','Identity','CreateDate')
})
$lvProx.Invoke([Action]{
Set-ListViewData $lvProx $prox @('Name','CredentialName','IsEnabled','Description')
})
Update-StatusBar "Objekte geladen von $($script:_ConnSrvName)" 'Success'
} -OnError {
param($err)
$btnConnect.Invoke([Action]{
$btnConnect.Enabled = $true; $btnConnect.Text = 'Verbinden'
})
$lblConnState.Invoke([Action]{
$lblConnState.Text = '* Fehler'
$lblConnState.ForeColor = [System.Drawing.Color]::FromArgb(220,53,69)
})
Update-StatusBar "Verbindungsfehler - Details im Fehler-Dialog" 'Error'
Show-ErrorDialog -Title 'Verbindungsfehler' -Message $err
}
})
$btnDisconnect.Add_Click({
$script:ActiveServer = $null
$lblConnState.Text = '* Nicht verbunden'
$lblConnState.ForeColor = [System.Drawing.Color]::FromArgb(220,53,69)
$btnDisconnect.Enabled = $false; $btnConnect.Text = 'Verbinden'
foreach ($lv in @($lvDbs,$lvLogins,$lvUsers,$lvLS,$lvJobs,$lvCreds,$lvProx)) {
$lv.Items.Clear()
}