forked from RaderSolutions/CWA-Git-Backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CWA-Git-Backup.ps1
1669 lines (1369 loc) · 62.3 KB
/
CWA-Git-Backup.ps1
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
<#
.SYNOPSIS
Backs up all LabTech scripts.
.DESCRIPTION
This script will export all LabTech scripts in xml format to a specified destination.
Requires the MySQL .NET connector.
.LINK
http://www.labtechconsulting.com
https://dev.mysql.com/downloads/connector/net/6.9.html
.OUTPUTS
Default values -
Log file stored in: $($env:windir)\LTScv\Logs\LT-ScriptExport.log
Scripts exported to: $($env:windir)\Program Files(x86)\LabTech\Backup\Scripts
Credentials file: $ScriptRoot
.NOTES
Version: 1.0
Author: Chris Taylor
Website: www.labtechconsulting.com
Creation Date: 9/11/2015
Purpose/Change: Initial script development
Version: 1.1
Author: Chris Taylor
Website: www.labtechconsulting.com
Creation Date: 9/23/2015
Purpose/Change: Added error catching
#>
#Requires -Version 3.0
Param(
[switch]$EmptyFolderOverride,
[switch]$ForceFullExport,
[switch]$RebuildGitConfig,
[switch]$Verbose = $True,
[switch]$SkipGitPull,
[switch]$RemoveGitLock = $True
)
#region-[Declarations]----------------------------------------------------------
$ScriptVersion = "2.0"
$ErrorActionPreference = "Stop"
$Verbose = $true
if ($SkipGitPull -ne $true) {$SkipGitPull = $false}
# Hack to handle ISE leaving $ScriptRoot blank
if ($PSScriptRoot -eq "") {$ScriptRoot = $psise.CurrentFile.FullPath | Split-Path} else {$ScriptRoot = $PSScriptRoot}
# Redirect all output from git on stderr to stdout so posh doesn't throw lots of red text to screen
$env:GIT_REDIRECT_STDERR = '2>&1'
#Get/Save config info
$ConfigFile = "$ScriptRoot\CWA-Git-Backup-Config.xml"
if($(Test-Path $ConfigFile) -eq $false) {
#Config file template
## DBSchemaExclusions - an array of regex to match. If matching, the whole match is removed
$Config = [xml]@'
<Settings>
<LogPath></LogPath>
<BackupRoot></BackupRoot>
<MySQLDatabase></MySQLDatabase>
<MySQLHost></MySQLHost>
<CredPath></CredPath>
<LastExport>0</LastExport>
<LTSharePath></LTSharePath>
<LTShareExtensionFilter>*.csv *.txt *.html *.xml *.htm *.log *.rtf *.ini *.sh *.ps1 *.psm1 *.inf *.vbs *.css *.bat *.js *.rdp *.crt *.reg *.cmd *.php</LTShareExtensionFilter>
<DBSchemaExclusions>
<a><![CDATA[[ ]+PARTITION.* VALUES LESS THAN .* ENGINE.*,]]></a>
<a><![CDATA[\(PARTITION.* VALUES LESS THAN .* ENGINE.*,]]></a>
<a><![CDATA[ PARTITION.* VALUES LESS THAN .* ENGINE.*\)]]></a>
<a><![CDATA[^[ ]+$]]></a>
</DBSchemaExclusions>
</Settings>
'@
try {
#Create config file
$default = "$($env:windir)\LTSvc\Logs"
$Config.Settings.LogPath = "$(Read-Host "Path of log file [$default]")"
if ($Config.Settings.LogPath -eq '') {$Config.Settings.LogPath = $default}
$default = "${env:ProgramFiles}\LabTech\Backup\CWA-Git-Backup"
$Config.Settings.BackupRoot = "$(Read-Host "Path of exported scripts [$default]")"
if ($Config.Settings.BackupRoot -eq '') {$Config.Settings.BackupRoot = $default}
$default = "labtech"
$Config.Settings.MySQLDatabase = "$(Read-Host "Name of LabTech database [$default]")"
if ($Config.Settings.MySQLDatabase -eq '') {$Config.Settings.MySQLDatabase = $default}
$default = "localhost"
if(Test-Path HKLM:\SOFTWARE\LabTech\Agent){
## DB Agent found, pulling sql server from there
$default = (get-itemproperty -path "HKLM:\SOFTWARE\LabTech\Agent" -name "SQLServer").SQLServer
}
$Config.Settings.MySQLHost = "$(Read-Host "FQDN of LabTech DB Server [$default]")"
if ($Config.Settings.MySQLHost -eq '') {$Config.Settings.MySQLHost = $default}
$default = $ScriptRoot
$Config.Settings.CredPath = "$(Read-Host "Path of credentials [$default]")"
if ($Config.Settings.CredPath -eq '') {$Config.Settings.CredPath = $default}
# Pull LTShare location from registry if possible, else default to default setting.
$default = (get-itemproperty -path "HKLM:\SOFTWARE\Wow6432Node\LabTech\Setup" -name "Local LTShare" -ErrorAction SilentlyContinue)."Local LTShare"
If ($default -eq $null) {$default = "c:\LTShare"}
$Config.Settings.LTSharePath = "$(Read-Host "Path to LTShare from this machine [$default]")"
if ($Config.Settings.LTSharePath -eq '') {$Config.Settings.LTSharePath = $default}
$Config.Save($ConfigFile)
}
Catch {
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Log-Error -LogPath $FullLogPath -ErrorDesc "Error durring config creation: $FailedItem, $ErrorMessage" -ExitGracefully $True
}
}
Else {
[xml]$Config = Get-Content $ConfigFile
}
#Location to credentials file
$CredPath = $Config.Settings.CredPath
$CredFile = "$CredPath\DBCredentials.xml"
#Get/Save user/password info
if ($(Test-Path $CredPath) -eq $false) {New-Item -ItemType Directory -Force -Path $CredPath | Out-Null}
if($(Test-Path $CredFile) -eq $false){
"Credentials file not found, building one now."
if(Test-Path HKLM:\SOFTWARE\LabTech\Agent){
$response = read-host "DB Agent found on this machine, get credentials from registry? [y/n] "
if($response -eq 'y'){
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -UseBasicParsing https://bit.ly/ltposh | Invoke-Expression
$Pass = (get-itemproperty -path "HKLM:\SOFTWARE\LabTech\Agent" -name "MySQLPass").MySQLPass
$PlaintextPass = ConvertFrom-LTSecurity $Pass
$User = (get-itemproperty -path "HKLM:\SOFTWARE\LabTech\Agent" -name "User").User
$SecurePassword = $PlaintextPass | ConvertTo-SecureString -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential -ArgumentList $User, $SecurePassword
}
if($creds){
"Creds decoded properly"
}else{
"Creds failed to decode"
$creds = Get-Credential -Message "Please provide the credentials to the CWA MySQL database."
}
}
$creds | Export-Clixml $CredFile -Force
}
#Log File Info
$LogName = "CWA-Export.log"
$LogPath = ($Config.Settings.LogPath)
$FullLogPath = [System.IO.Path]::Combine($LogPath, $LogName)
#Robocopy Log File Info
$LogNameRobo = "CWA-Export-robocopy.log"
$LogPath = ($Config.Settings.LogPath)
$FullLogPathRobo = [System.IO.Path]::Combine($LogPath, $LogNameRobo)
#Location to the backp repository
$BackupRoot = $Config.Settings.BackupRoot
#MySQL connection info
$MySQLDatabase = $Config.Settings.MySQLDatabase
$MySQLHost = $Config.Settings.MySQLHost
try {
$MySQLAdminPassword = (IMPORT-CLIXML $CredFile).GetNetworkCredential().Password
$MySQLAdminUserName = (IMPORT-CLIXML $CredFile).GetNetworkCredential().UserName
} catch {
Write-Error "ERROR: Unable to decrypt DB credential file. Most likely you're not the Windows user that created it. Log in as that user and try again."
}
if($ForceFullExport){
$Config.Settings.LastExport = "0"
$EmptyFolderOverride = $true
}
#endregion
#region-[Functions]------------------------------------------------------------
Function New-BackupPath {
Param (
[Parameter(Mandatory=$true)][string]$NewPath
)
$BackupPath = [System.IO.Path]::Combine($BackupRoot, $NewPath)
New-Item -ItemType Directory -Force -Path $BackupPath | Out-Null
Set-Location $BackupPath
Return $BackupPath
}
Function Export-DBSchema {
Param(
[switch]$info_schema,
[Parameter(Mandatory=$true,Position=1)][string]$BackupPath,
[Parameter(Mandatory=$true,Position=2)][string]$nameCol,
[Parameter(Mandatory=$true,Position=3)][string]$createCol,
[Parameter(Mandatory=$true,Position=4)][string]$createSQLQueryPrefix,
[Parameter(Mandatory=$true,Position=5)][string]$listSQLQuery
)
if($info_schema){
$rows = Get-SQLData $listSQLQuery -info_schema
}else{
$rows = Get-SQLData $listSQLQuery
}
foreach($row in $rows.$nameCol){
$filename = [System.IO.Path]::Combine($BackupPath, "$row.sql")
$SQLQuery = "$createSQLQueryPrefix ``$MySqlDataBase``.``$row``"
## silent continue due to certain tables failing to export config
## replace the auto_increment field to have sane diffs
if($info_schema){
$FileContent = (Get-SQLData $SQLQuery -info_schema -ErrorAction SilentlyContinue).$createCol | %{$_ -replace ' AUTO_INCREMENT=[0-9]*\b',''}
}else{
$FileContent = (Get-SQLData $SQLQuery -ErrorAction SilentlyContinue).$createCol | %{$_ -replace ' AUTO_INCREMENT=[0-9]*\b',''}
}
## convert to string array
$FileContentReal = ($FileContent -replace "`r").split("`n")
foreach($Exclusion in $Config.Settings.DBSchemaExclusions.a.'#cdata-section'){
## way too noisy
#if($Verbose){Log-Write -FullLogPath $FullLogPath -LineValue "Filtering [$Exclusion] from $filename"}
try{
$FileContentReal = $FileContentReal | % {$_ -replace $Exclusion,''}
}catch{
$ErrorMessage = $_.Exception.Message
Log-Error -FullLogPath $FullLogPath -ErrorDesc "Processing db exclusion [$Exclusion] from $filename - $ErrorMessage" -ExitGracefully $False
}
}
## exclude empty strings
$content = $FileContentReal | ? {$_ -ne ''}
[IO.File]::WriteAllLines($filename, $content)
}
get-ChildItem $BackupPath -File | ? {($_.name -replace '\.sql','') -notin $rows.$nameCol} | remove-item -Force
}
function Format-Xml {
<#
.SYNOPSIS
Format the incoming object as the text of an XML document.
from https://blogs.msdn.microsoft.com/sergey_babkins_blog/2016/12/31/how-to-pretty-print-xml-in-powershell-and-text-pipelines/
#>
param(
## Text of an XML document.
[Parameter(ValueFromPipeline = $true)]
[string[]]$Text
)
begin {
$data = New-Object System.Collections.ArrayList
}
process {
[void] $data.Add($Text -join "`n")
}
end {
$doc=New-Object System.Xml.XmlDataDocument
$doc.LoadXml($data -join "`n")
$sw=New-Object System.Io.Stringwriter
$writer=New-Object System.Xml.XmlTextWriter($sw)
$writer.Formatting = [System.Xml.Formatting]::Indented
$doc.WriteContentTo($writer)
$sw.ToString()
}
}
Function Log-Start{
<#
.SYNOPSIS
Creates log file
.DESCRIPTION
Creates log file with path and name that is passed. Checks if log file exists, and if it does deletes it and creates a new one.
Once created, writes initial logging data
.PARAMETER LogPath
Mandatory. Path of where log is to be created. Example: C:\Windows\Temp
.PARAMETER LogName
Mandatory. Name of log file to be created. Example: Test_Script.log
.PARAMETER ScriptVersion
Mandatory. Version of the running script which will be written in the log. Example: 1.5
.INPUTS
Parameters above
.OUTPUTS
Log file created
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support
Version: 1.2
Author: Chris Taylor
Creation Date: 7/17/2015
Purpose/Change: Added directory creation if not present.
Added Append option
.EXAMPLE
Log-Start -LogPath "C:\Windows\Temp" -LogName "Test_Script.log" -ScriptVersion "1.5"
#>
[CmdletBinding()]
Param ([Parameter(Mandatory=$true)][string]$LogPath, [Parameter(Mandatory=$true)][string]$LogName, [Parameter(Mandatory=$true)][string]$ScriptVersion, [Parameter(Mandatory=$false)][switch]$Append)
Process{
$FullLogPath = [System.IO.Path]::Combine($LogPath, $LogName)
#Check if file exists and delete if it does
If((Test-Path -Path $FullLogPath) -and $Append -ne $true){
Remove-Item -Path $FullLogPath -Force
}
#Check if folder exists if not create
If((Test-Path -PathType Container -Path $LogPath) -eq $False){
New-Item -ItemType Directory -Force -Path $LogPath | Out-Null
}
#Create file and start logging
If($(Test-Path -Path $FullLogPath) -ne $true) {
New-Item -Path $LogPath -Name $LogName -ItemType File | Out-Null
}
Add-Content -Path $FullLogPath -Value "***************************************************************************************************"
Add-Content -Path $FullLogPath -Value "Started processing at [$([DateTime]::Now)]."
Add-Content -Path $FullLogPath -Value "***************************************************************************************************"
Add-Content -Path $FullLogPath -Value ""
Add-Content -Path $FullLogPath -Value "Running script version [$ScriptVersion]."
Add-Content -Path $FullLogPath -Value ""
Add-Content -Path $FullLogPath -Value "***************************************************************************************************"
Add-Content -Path $FullLogPath -Value ""
#Write to screen for debug mode
Write-Debug "***************************************************************************************************"
Write-Debug "Started processing at [$([DateTime]::Now)]."
Write-Debug "***************************************************************************************************"
Write-Debug ""
Write-Debug "Running script version [$ScriptVersion]."
Write-Debug ""
Write-Debug "***************************************************************************************************"
Write-Debug ""
}
}
Function Log-Write{
<#
.SYNOPSIS
Writes to a log file
.DESCRIPTION
Appends a new line to the end of the specified log file
.PARAMETER LogPath
Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER LineValue
Mandatory. The string that you want to write to the log
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support
.EXAMPLE
Log-Write -FullLogPath "C:\Windows\Temp\Test_Script.log" -LineValue "This is a new line which I am appending to the end of the log file."
#>
[CmdletBinding()]
Param ([Parameter(Mandatory=$true)][string]$FullLogPath, [Parameter(Mandatory=$true)][string]$LineValue)
Process{
Add-Content -Path $FullLogPath -Value $LineValue
Write-Output $LineValue
#Write to screen for debug mode
Write-Debug $LineValue
}
}
Function Log-Error{
<#
.SYNOPSIS
Writes an error to a log file
.DESCRIPTION
Writes the passed error to a new line at the end of the specified log file
.PARAMETER FullLogPath
Mandatory. Full path of the log file you want to write to. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER ErrorDesc
Mandatory. The description of the error you want to pass (use $_.Exception)
.PARAMETER ExitGracefully
Mandatory. Boolean. If set to True, runs Log-Finish and then exits script
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support. Added -ExitGracefully parameter functionality
.EXAMPLE
Log-Error -FullLogPath "C:\Windows\Temp\Test_Script.log" -ErrorDesc $_.Exception -ExitGracefully $True
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory=$true)][string]$FullLogPath,
[Parameter(Mandatory=$true)][string]$ErrorDesc,
[Parameter(Mandatory=$true)][boolean]$ExitGracefully
)
Process{
Add-Content -Path $FullLogPath -Value "Error: An error has occurred [$ErrorDesc]."
#Write to screen for debug mode
Write-Debug "Error: An error has occurred [$ErrorDesc]."
#If $ExitGracefully = True then run Log-Finish and exit script
If ($ExitGracefully -eq $True){
Write-Error $ErrorDesc
Log-Finish -FullLogPath $FullLogPath -Limit 50000
Break
}
}
}
Function Log-Finish{
<#
.SYNOPSIS
Write closing logging data & exit
.DESCRIPTION
Writes finishing logging data to specified log and then exits the calling script
.PARAMETER LogPath
Mandatory. Full path of the log file you want to write finishing data to. Example: C:\Windows\Temp\Test_Script.log
.PARAMETER NoExit
Optional. If this is set to True, then the function will not exit the calling script, so that further execution can occur
.PARAMETER Limit
Optional. Sets the max linecount of the script.
.INPUTS
Parameters above
.OUTPUTS
None
.NOTES
Version: 1.0
Author: Luca Sturlese
Creation Date: 10/05/12
Purpose/Change: Initial function development
Version: 1.1
Author: Luca Sturlese
Creation Date: 19/05/12
Purpose/Change: Added debug mode support
Version: 1.2
Author: Luca Sturlese
Creation Date: 01/08/12
Purpose/Change: Added option to not exit calling script if required (via optional parameter)
Version: 1.3
Author: Chris Taylor
Creation Date: 7/17/2015
Purpose/Change: Added log line count limit.
.EXAMPLE
Log-Finish -FullLogPath "C:\Windows\Temp\Test_Script.log"
.EXAMPLE
Log-Finish -FullLogPath "C:\Windows\Temp\Test_Script.log" -NoExit $True
#>
[CmdletBinding()]
Param ([Parameter(Mandatory=$true)][string]$FullLogPath, [Parameter(Mandatory=$false)][string]$NoExit, [Parameter(Mandatory=$false)][int]$Limit )
Process{
Add-Content -Path $FullLogPath -Value ""
Add-Content -Path $FullLogPath -Value "***************************************************************************************************"
Add-Content -Path $FullLogPath -Value "Finished processing at [$([DateTime]::Now)]."
Add-Content -Path $FullLogPath -Value "***************************************************************************************************"
#Write to screen for debug mode
Write-Debug ""
Write-Debug "***************************************************************************************************"
Write-Debug "Finished processing at [$([DateTime]::Now)]."
Write-Debug "***************************************************************************************************"
if ($Limit){
#Limit Log file to XX lines
## roll logs instead of truncate
(Get-Content $FullLogPath -tail $Limit -readcount 0) | Set-Content $FullLogPath -Force -Encoding Unicode
}
#Exit calling script if NoExit has not been specified or is set to False
If(!($NoExit) -or ($NoExit -eq $False)){
Exit
}
}
}
Function Get-SQLData {
<#
.SYNOPSIS
Executes a MySQL query aginst the LabTech Databse.
.DESCRIPTION
This comandlet will execute a MySQL query aginst the LabTech database.
Requires the MySQL .NET connector.
Original script by Dan Rose
.LINK
https://dev.mysql.com/downloads/connector/net/6.9.html
https://www.cogmotive.com/blog/powershell/querying-mysql-from-powershell
http://www.labtechconsulting.com
.PARAMETER Query
Input your MySQL query in double quotes.
.INPUTS
Pipeline
.NOTES
Version: 1.0
Author: Chris Taylor
Website: www.labtechconsulting.com
Creation Date: 9/11/2015
Purpose/Change: Initial script development
.EXAMPLE
Get-SQLData "SELECT ScriptID FROM lt_scripts"
$Query | Get-SQLData
#>
Param(
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true)]
[string]$Query,
[switch]$info_schema
)
Begin {
$ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" + $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword
if(-not $info_schema){
$ConnectionString += ";database="+$MySQLDatabase
}else{
$ConnectionString += ";database=information_schema"
}
}
Process {
Try {
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
$DataSet.Tables[0]
}
Catch {
Log-Error -FullLogPath $FullLogPath -ErrorDesc "Unable to run query : $query" -ExitGracefully $False
}
}
End {
$Connection.Close()
}
}
function Get-CompressedByteArray {
##############################
#.SYNOPSIS
#Function pulled from example script: https://gist.github.com/marcgeld/bfacfd8d70b34fdf1db0022508b02aca
#
#.DESCRIPTION
#Long description
#
#.PARAMETER byteArray
#Parameter description
#
#.EXAMPLE
#An example
#
#.NOTES
#General notes
##############################
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[byte[]] $byteArray = $(Throw("-byteArray is required"))
)
Process {
Write-Verbose "Get-CompressedByteArray"
[System.IO.MemoryStream] $output = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)
$gzipStream.Write( $byteArray, 0, $byteArray.Length )
$gzipStream.Close()
$output.Close()
$tmp = $output.ToArray()
Write-Output $tmp
}
}
function Get-DecompressedByteArray {
##############################
#.SYNOPSIS
#Function pulled from example script: https://gist.github.com/marcgeld/bfacfd8d70b34fdf1db0022508b02aca
#
#.DESCRIPTION
#Long description
#
#.PARAMETER byteArray
#Parameter description
#
#.EXAMPLE
#An example
#
#.NOTES
#General notes
##############################
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[byte[]] $byteArray = $(Throw("-byteArray is required"))
)
Process {
Write-Verbose "Get-DecompressedByteArray"
$input = New-Object System.IO.MemoryStream( , $byteArray )
$output = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress)
$gzipStream.CopyTo( $output )
$gzipStream.Close()
$input.Close()
[byte[]] $byteOutArray = $output.ToArray()
Write-Output $byteOutArray
}
}
Function Unpack-LTXML {
<#
.SYNOPSIS
Unpacks an LT XML export to include ScriptData and LicenseData in human-readable format.
.DESCRIPTION
This commandlet will read an LT XML file and replace ScriptData and LicenseData
.PARAMETER FileName
Full name of exported XML script. Will be read and re-written as $FileName -replace "\.xml$",".unpacked.xml"
.NOTES
.EXAMPLE
Unpack-LTXML -FileName c:\test\ltscript.xml
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$FileName
)
#Write-Output "Unpacking script: $FileName"
[System.Text.Encoding] $enc = [System.Text.Encoding]::UTF8
$xmlcontent = [xml](Get-Content $FileName)
$data = $xmlcontent.LabTech_Expansion.PackedScript.NewDataSet.Table.LicenseData
[byte[]]$dataByteArray = [System.Convert]::FromBase64String($data)
$decompressedByteArray = Get-DecompressedByteArray -byteArray $dataByteArray
$xmlData = [xml]($enc.GetString( $decompressedByteArray ))
$null = $xmlcontent.LabTech_Expansion.PackedScript.NewDataSet.Table.AppendChild($xmlcontent.ImportNode($xmlData.LicenseData,$true))
$data = $xmlcontent.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptData
[byte[]]$dataByteArray = [System.Convert]::FromBase64String($data)
$decompressedByteArray = Get-DecompressedByteArray -byteArray $dataByteArray
$xmlData = [xml]($enc.GetString( $decompressedByteArray ))
# Replace actionIDs, functionids, etc with names and descriptions
foreach($ScriptStep in $($xmlData.ScriptData.ScriptSteps)){
$null = $ScriptStep.RemoveChild($ScriptStep.SelectSingleNode('Sort'))
foreach($type in "action","FunctionID","Continue","OSLimit"){
$typeDetails = $null
switch($type){
"action" {$typeDetails = $scriptFunctionConstantsPSObject.Actions."$($ScriptStep.$type)"}
"FunctionID" {$typeDetails = $scriptFunctionConstantsPSObject.Functions."$($ScriptStep.$type)".Name}
"Continue" {$typeDetails = $scriptFunctionConstantsPSObject.Continues."$($ScriptStep.$type)"}
"OSLimit" {$typeDetails = $scriptFunctionConstantsPSObject.OSLimits."$($ScriptStep.$type)"}
}
if($typeDetails -eq $null ){
$typeDetails = "Script step metadata type details unknown for id: $($ScriptStep.$type)"
}
$ScriptStep.$type = $typeDetails
}
}
$null = $xmlcontent.LabTech_Expansion.PackedScript.NewDataSet.Table.AppendChild($xmlcontent.ImportNode($xmlData.ScriptData,$true))
$xmlcontent.Save($($FileName -replace "\.xml$",".unpacked.xml"))
}
Function Update-TableOfContents {
<#
.SYNOPSIS
Creates a table of contents for the LT scripts. This will capture script moves as well as provide links to the script xml
.PARAMETER FileName
Full name of ToC file.
.NOTES
.EXAMPLE
Update-TableOfContents -FileName c:\test\ToC.md
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$FileName
)
$ToCData = @()
$ToCata += "## Use this table of contents to jump to details of a script"
## output all scripts at base of script tree above all other folders
$FolderScripts = Get-SQLData -query "SELECT * FROM lt_scripts WHERE FolderID=0 ORDER BY ScriptName "
foreach($FolderScript in $FolderScripts){
$LastUser = $FolderScript.Last_User.Substring(0, $FolderScript.Last_User.IndexOf('@'))
$ScriptPath = "$([math]::floor($FolderScript.ScriptID / 50) * 50)/$($FolderScript.ScriptID).unpacked.xml"
$LastDate = $FolderScript.Last_Date.ToString("yyyy-MM-dd_HH-mm-ss")
$TOCData += ">"*$Depth + ">" + "-Script: [$($FolderScript.ScriptName)]($ScriptPath) - Last Modified By: $LastUser on $LastDate" + " "
}
$ToCData += Write-FolderTree -Depth 0 -ParentID 0
[IO.File]::WriteAllLines($filename, $ToCData)
}
Function Write-FolderTree {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$Depth,
[Parameter(Mandatory=$True,Position=2)]
[string]$ParentID
)
<#
Writes the folder structure in ASCII, with the initial indention of the Depth param:
+---A
| +---A
| \---B
+---B
| \---A
| \---A
\---C
#>
$Folders = Get-SQLData -query "SELECT * FROM scriptfolders WHERE ParentID=$ParentID ORDER BY name "
foreach($Folder in $Folders){
# Output this folder at the right level
<#
"<details><summary>"
if($Folder.FolderId -ne $Folders[$Folders.count - 1].FolderID){
"-"*$Depth + "+" + "-" + $Folder.name
}else{
"-"*$Depth + "\" + "-" + $Folder.name
}
"</summary>"
""
#>
# insert newline before each folder
" "
">"*$Depth + $Folder.name + " "
# Insert all folders inside of this folder
Write-FolderTree -Depth ($Depth + 1) -ParentID $Folder.FolderID
# Insert Script links
$FolderScripts = Get-SQLData -query "SELECT * FROM lt_scripts WHERE FolderID=$($Folder.FolderID) ORDER BY ScriptName "
foreach($FolderScript in $FolderScripts){
$LastUser = $FolderScript.Last_User.Substring(0, $FolderScript.Last_User.IndexOf('@'))
$ScriptPath = "$([math]::floor($FolderScript.ScriptID / 50) * 50)/$($FolderScript.ScriptID).unpacked.xml"
$LastDate = $FolderScript.Last_Date.ToString("yyyy-MM-dd_HH-mm-ss")
">"*$Depth + ">" + "-Script: [$($FolderScript.ScriptName)]($ScriptPath) - Last Modified By: $LastUser on $LastDate" + " "
}
#"</details>"
}
}
Function Export-LTScript {
<#
.SYNOPSIS
Exports a LabTech script as an xml file.
.DESCRIPTION
This commandlet will execute a MySQL query aginst the LabTech database.
Requires Get-SQLData
.LINK
http://www.labtechconsulting.com
.PARAMETER Query
Input your MySQL query in double quotes.
.PARAMETER FilePath
File path of exported script.
.NOTES
Version: 1.0
Author: Chris Taylor
Website: www.labtechconsulting.com
Creation Date: 9/11/2015
Purpose/Change: Initial script development
.EXAMPLE
Get-SQLData "SELECT ScriptID FROM lt_scripts" -FilePath C:\Windows\Temp
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$ScriptID
)
#LabTech XML template
$ExportTemplate = [xml] @"
<LabTech_Expansion
Version="100.332"
Name="LabTech Script Expansion"
Type="PackedScript">
<PackedScript>
<NewDataSet>
<Table>
<ScriptId></ScriptId>
<FolderId></FolderId>
<ScriptName></ScriptName>
<ScriptNotes></ScriptNotes>
<Permission></Permission>
<EditPermission></EditPermission>
<ComputerScript></ComputerScript>
<LocationScript></LocationScript>
<MaintenanceScript></MaintenanceScript>
<FunctionScript></FunctionScript>
<LicenseData></LicenseData>
<ScriptData></ScriptData>
<ScriptVersion></ScriptVersion>
<ScriptGuid></ScriptGuid>
<ScriptFlags></ScriptFlags>
<Parameters></Parameters>
</Table>
</NewDataSet>
<ScriptFolder>
<NewDataSet>
<Table>
<FolderID></FolderID>
<ParentID></ParentID>
<Name></Name>
<GUID></GUID>
</Table>
</NewDataSet>
</ScriptFolder>
</PackedScript>
</LabTech_Expansion>
"@
#Query MySQL for script data.
$ScriptXML = Get-SQLData -query "SELECT * FROM lt_scripts WHERE ScriptID=$ScriptID"
$ScriptData = Get-SQLData -query "SELECT CONVERT(ScriptData USING utf8) AS Data FROM lt_scripts WHERE ScriptID=$ScriptID"
$ScriptLicense = Get-SQLData -query "SELECT CONVERT(LicenseData USING utf8) AS License FROM lt_scripts WHERE ScriptID=$ScriptID"
$LTVersion = Get-SQLData -Query "SELECT CONCAT(majorversion,'.',minorversion) AS LTVersion FROM config"
#Save script data to the template.
$ExportTemplate.LabTech_Expansion.Version = "$($LTVersion.LTVersion)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptId = "$($ScriptXML.ScriptId)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.FolderId = "$($ScriptXML.FolderId)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptName = "$($ScriptXML.ScriptName)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptNotes = "$($ScriptXML.ScriptNotes)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.Permission = "$($ScriptXML.Permission)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.EditPermission = "$($ScriptXML.EditPermission)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ComputerScript = "$($ScriptXML.ComputerScript)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.LocationScript = "$($ScriptXML.LocationScript)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.MaintenanceScript = "$($ScriptXML.MaintenanceScript)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.FunctionScript = "$($ScriptXML.FunctionScript)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.LicenseData = "$($ScriptLicense.License)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptData = "$($ScriptData.Data)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptVersion = "$($ScriptXML.ScriptVersion)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptGuid = "$($ScriptXML.ScriptGuid)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.ScriptFlags = "$($ScriptXML.ScriptFlags)"
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.Parameters = "$($ScriptXML.Parameters)"
#Check folder information
#Check if script is at root and not in a folder
If ($($ScriptXML.FolderId) -eq 0 -or !$($ScriptXML.FolderId)) {
try {
#Delete folder information from template
$ExportTemplate.LabTech_Expansion.PackedScript.ScriptFolder.RemoveAll()
}
Catch {
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Log-Error -FullLogPath $FullLogPath -ErrorDesc "Unable to remove folder data from XML: $FailedItem, $ErrorMessage" -ExitGracefully $True
}
}
Else {
#Query MySQL for folder data.
$FolderData = Get-SQLData -query "SELECT * FROM `scriptfolders` WHERE FolderID=$($ScriptXML.FolderId)"
#Check if folder is no longer present.
if ($FolderData -eq $null) {
Log-Write -FullLogPath $FullLogPath -LineValue "ScriptID $($ScriptXML.ScriptId) named '$($ScriptXML.ScriptName)' references folder $($ScriptXML.FolderId), this folder is no longer present. Setting to root folder."
Log-Write -FullLogPath $FullLogPath -LineValue "It is recomended that you move this script to a folder."
#Set to FolderID 0
$ExportTemplate.LabTech_Expansion.PackedScript.NewDataSet.Table.FolderId = "0"
$ScriptXML.FolderID = 0
try {
#Delete folder information from template
$ExportTemplate.LabTech_Expansion.PackedScript.ScriptFolder.RemoveAll()
}
Catch {
$ErrorMessage = $_.Exception.Message
$FailedItem = $_.Exception.ItemName
Log-Error -FullLogPath $FullLogPath -ErrorDesc "Unable to remove folder data from XML: $FailedItem, $ErrorMessage" -ExitGracefully $True
}
}
Else {
#Format the folder name.
#Remove special characters
$FolderName = $($FolderData.Name).Replace('*','')
$FolderName = $FolderName.Replace('/','-')
$FolderName = $FolderName.Replace('<','')
$FolderName = $FolderName.Replace('>','')
$FolderName = $FolderName.Replace(':','')
$FolderName = $FolderName.Replace('"','')
$FolderName = $FolderName.Replace('\','-')