forked from ztrhgf/Powershell_CICD_repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stp.ps1
2002 lines (1725 loc) · 89.8 KB
/
stp.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
#Requires -Version 5.1
#FIXME predelat na auth pomoci PAT
<#
.SYNOPSIS
Installation script for PowerShell managing solution hosted at https://github.com/ztrhgf/Powershell_CICD_repository
Contains same steps as described at https://github.com/ztrhgf/Powershell_CICD_repository/blob/master/1.%20HOW%20TO%20INSTALL.md
.DESCRIPTION
Installation script for PowerShell managing solution hosted at https://github.com/ztrhgf/Powershell_CICD_repository
Contains same steps as described at https://github.com/ztrhgf/Powershell_CICD_repository/blob/master/1.%20HOW%20TO%20INSTALL.md
.PARAMETER noEnvModification
Switch to omit changes of your environment i.e. just customization of cloned folders content 'repo_content_set_up' will be made.
.PARAMETER iniFile
Path to text ini file that this script uses as storage for values the user entered during this scripts run.
So next time, they can be used to speed up whole installation process.
Default is "Powershell_CICD_repository.ini" in root of user profile, so it can't be replaced when user reset cloned repository etc.
.NOTES
Author: Ondřej Šebela - [email protected]
#>
[CmdletBinding()]
param (
[switch] $noEnvModification
,
[string] $iniFile = (Join-Path $env:USERPROFILE "Powershell_CICD_repository.ini")
)
Begin {
$Host.UI.RawUI.WindowTitle = "Installer of PowerShell CI/CD solution"
$transcript = Join-Path $env:USERPROFILE ((Split-Path $PSCommandPath -Leaf) + ".log")
$null = Start-Transcript $transcript -Force
$ErrorActionPreference = "Stop"
#region Variables
$isserver = $notadmin = $notadadmin = $noadmodule = $nogpomodule = $skipad = $skipgpo = $mgmserver = $accessdenied = $repositoryhostsession = $mgmserversession = 0
# char that is between name of variable and its value in ini file
$divider = "="
# list of variables needed for installation, will be saved to iniFile
$setupVariable = @{}
# name of GPO that will be used for connecting computers to this solution
$GPOname = 'PS_env_set_up'
$userRepositoryWasntEmpty = $false
# hardcoded PATHs for TEST installation
$remoteRepository = "$env:SystemDrive\myCompanyRepository_remote"
#endregion Variables
# Detect if Server
if ((Get-WmiObject -Class Win32_OperatingSystem).ProductType -in (2, 3)) {
++$isServer
}
#region helper functions
function _pressKeyToContinue {
Write-Host "`nPress any key to continue" -NoNewline
$null = [Console]::ReadKey('?')
}
function _continue {
param ($text, [switch] $passthru)
$t = "Continue? (Y|N)"
if ($text) {
$t = "$text. $t"
}
$choice = ""
while ($choice -notmatch "^[Y|N]$") {
$choice = Read-Host $t
}
if ($choice -eq "N") {
if ($passthru) {
return $choice
} else {
break
}
}
if ($passthru) {
return $choice
}
}
function _skip {
param ($text)
$t = "Skip? (Y|N)"
if ($text) {
$t = "$text. $t"
}
$t = "`n$t"
$choice = ""
while ($choice -notmatch "^[Y|N]$") {
$choice = Read-Host $t
}
if ($choice -eq "N") {
return $false
} else {
return $true
}
}
function _getComputerMembership {
# Pull the gpresult for the current server
$Lines = & "$env:windir\system32\gpresult.exe" /s $env:COMPUTERNAME /v /SCOPE COMPUTER
# Initialize arrays
$cgroups = @()
# Out equals false by default
$Out = $False
# Define start and end lines for the section we want
$start = "The computer is a part of the following security groups"
$end = "Resultant Set Of Policies for Computer"
# Loop through the gpresult output looking for the computer security group section
ForEach ($Line In $Lines) {
If ($Line -match $start) { $Out = $True }
If ($Out -eq $True) { $cgroups += $Line }
If ($Line -match $end) { Break }
}
$cgroups | % { $_.trim() }
}
function _startProcess {
[CmdletBinding()]
param (
[string] $filePath = ''
,
[string] $argumentList = ''
,
[string] $workingDirectory = (Get-Location)
,
[switch] $dontWait
,
# lot of git commands output verbose output to error stream
[switch] $outputErr2Std
)
$p = New-Object System.Diagnostics.Process
$p.StartInfo.UseShellExecute = $false
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.RedirectStandardError = $true
$p.StartInfo.WorkingDirectory = $workingDirectory
$p.StartInfo.FileName = $filePath
$p.StartInfo.Arguments = $argumentList
[void]$p.Start()
if (!$dontWait) {
$p.WaitForExit()
}
$p.StandardOutput.ReadToEnd()
if ($outputErr2Std) {
$p.StandardError.ReadToEnd()
} else {
if ($err = $p.StandardError.ReadToEnd()) {
Write-Error $err
}
}
}
function _setVariable {
# function defines variable and fills it with value find in ini file or entered by the user
param ([string] $variable, [string] $readHost, [switch] $YNQuestion, [switch] $optional, [switch] $passThru)
$value = $setupVariable.GetEnumerator() | ? { $_.name -eq $variable -and $_.value } | select -ExpandProperty value
if (!$value) {
if ($YNQuestion) {
$value = ""
while ($value -notmatch "^[Y|N]$") {
$value = Read-Host " - $readHost (Y|N)"
}
} else {
if ($optional) {
$value = Read-Host " - (OPTIONAL) Enter $readHost"
} else {
while (!$value) {
$value = Read-Host " - Enter $readHost"
}
}
}
} else {
# Write-Host " - variable '$variable' will be: $value" -ForegroundColor Gray
}
if ($value) {
# replace whitespaces so as quotes
$value = $value -replace "^\s*|\s*$" -replace "^[`"']*|[`"']*$"
$setupVariable.$variable = $value
New-Variable $variable $value -Scope script -Force -Confirm:$false
} else {
if (!$optional) {
throw "Variable $variable is mandatory!"
}
}
if ($passThru) {
return $value
}
}
function _unsetVariable {
# function defines variable and fills it with value find in ini file or entered by the user
param ([string] $variable)
$setupVariable.$variable = $null
}
function _setVariableValue {
# function defines variable and fills it with given value
param ([string] $variable, $value, [switch] $passThru)
if (!$value) { throw "Undefined value" }
# replace whitespaces so as quotes
$value = $value -replace "^\s*|\s*$" -replace "^[`"']*|[`"']*$"
$setupVariable.$variable = $value
New-Variable $variable $value -Scope script -Force -Confirm:$false
if ($passThru) {
return $value
}
}
function _saveInput {
# call after each successfully ended section, so just correct inputs will be stored
if (Test-Path $iniFile -ErrorAction SilentlyContinue) {
Remove-Item $iniFile -Force -Confirm:$false
}
$setupVariable.GetEnumerator() | % {
if ($_.name -and $_.value) {
$_.name + "=" + $_.value | Out-File $iniFile -Append -Encoding utf8
}
}
}
function _setPermissions {
[cmdletbinding()]
param (
[Parameter(Mandatory = $true)]
[string] $path
,
$readUser
,
$writeUser
,
[switch] $resetACL
)
if (!(Test-Path $path)) {
throw "Path isn't accessible"
}
$permissions = @()
if (Test-Path $path -PathType Container) {
# it is folder
$acl = New-Object System.Security.AccessControl.DirectorySecurity
if ($resetACL) {
# reset ACL, i.e. remove explicit ACL and enable inheritance
$acl.SetAccessRuleProtection($false, $false)
} else {
# disable inheritance and remove inherited ACL
$acl.SetAccessRuleProtection($true, $false)
if ($readUser) {
$readUser | ForEach-Object {
$permissions += @(, ("$_", 'ReadAndExecute', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
}
}
if ($writeUser) {
$writeUser | ForEach-Object {
$permissions += @(, ("$_", 'FullControl', 'ContainerInherit,ObjectInherit', 'None', 'Allow'))
}
}
}
} else {
# it is file
$acl = New-Object System.Security.AccessControl.FileSecurity
if ($resetACL) {
# reset ACL, ie remove explicit ACL and enable inheritance
$acl.SetAccessRuleProtection($false, $false)
} else {
# disable inheritance and remove inherited ACL
$acl.SetAccessRuleProtection($true, $false)
if ($readUser) {
$readUser | ForEach-Object {
$permissions += @(, ("$_", 'ReadAndExecute', 'Allow'))
}
}
if ($writeUser) {
$writeUser | ForEach-Object {
$permissions += @(, ("$_", 'FullControl', 'Allow'))
}
}
}
}
$permissions | ForEach-Object {
$ace = New-Object System.Security.AccessControl.FileSystemAccessRule $_
$acl.AddAccessRule($ace)
}
try {
# Set-Acl cannot be used because of bug https://stackoverflow.com/questions/31611103/setting-permissions-on-a-windows-fileshare
(Get-Item $path).SetAccessControl($acl)
} catch {
throw "There was an error when setting NTFS rights: $_"
}
}
function _copyFolder {
[cmdletbinding()]
Param (
[string] $source
,
[string] $destination
,
[string] $excludeFolder = ""
,
[switch] $mirror
)
Begin {
[Void][System.IO.Directory]::CreateDirectory($destination)
}
Process {
if ($mirror) {
$result = & "$env:windir\system32\robocopy.exe" "$source" "$destination" /MIR /E /NFL /NDL /NJH /R:4 /W:5 /XD "$excludeFolder"
} else {
$result = & "$env:windir\system32\robocopy.exe" "$source" "$destination" /E /NFL /NDL /NJH /R:4 /W:5 /XD "$excludeFolder"
}
$copied = 0
$failures = 0
$duration = ""
$deleted = @()
$errMsg = @()
$result | ForEach-Object {
if ($_ -match "\s+Dirs\s+:") {
$lineAsArray = (($_.Split(':')[1]).trim()) -split '\s+'
$copied += $lineAsArray[1]
$failures += $lineAsArray[4]
}
if ($_ -match "\s+Files\s+:") {
$lineAsArray = ($_.Split(':')[1]).trim() -split '\s+'
$copied += $lineAsArray[1]
$failures += $lineAsArray[4]
}
if ($_ -match "\s+Times\s+:") {
$lineAsArray = ($_.Split(':', 2)[1]).trim() -split '\s+'
$duration = $lineAsArray[0]
}
if ($_ -match "\*EXTRA \w+") {
$deleted += @($_ | ForEach-Object { ($_ -split "\s+")[-1] })
}
if ($_ -match "^ERROR: ") {
$errMsg += ($_ -replace "^ERROR:\s+")
}
# captures errors like: 2020/04/27 09:01:27 ERROR 2 (0x00000002) Accessing Source Directory C:\temp
if ($match = ([regex]"^[0-9 /]+ [0-9:]+ ERROR \d+ \([0-9x]+\) (.+)").Match($_).captures.groups) {
$errMsg += $match[1].value
}
}
return [PSCustomObject]@{
'Copied' = $copied
'Failures' = $failures
'Duration' = $duration
'Deleted' = $deleted
'ErrMsg' = $errMsg
}
}
}
function _installGIT {
$installedGITVersion = ( (Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*) + (Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*) | ? { $_.DisplayName -and $_.Displayname -match '^Git' }) | select -ExpandProperty DisplayVersion
if (!$installedGITVersion -or $installedGITVersion -as [version] -lt "2.27.0") {
# get latest download url for git-for-windows 64-bit exe
$url = "https://api.github.com/repos/git-for-windows/git/releases/latest"
if ($asset = Invoke-RestMethod -Method Get -Uri $url | % { $_.assets } | ? { $_.name -like "*64-bit.exe" }) {
# Download Git Installer File
" - downloading"
$installer = "$env:temp\$($asset.name)"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest $asset.browser_download_url -OutFile $installer
$ProgressPreference = 'Continue'
# Install Git
" - installing"
$install_args = "/SP- /VERYSILENT /SUPPRESSMSGBOXES /NOCANCEL /NORESTART /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS"
Start-Process -FilePath $installer -ArgumentList $install_args -Wait
Start-Sleep 3
# update PATH
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")
} else {
Write-Warning "Skipped!`nURL $url isn't accessible, install GIT manually"
_continue
}
} else {
" - already installed"
}
}
function _installGITCredManager {
$ErrorActionPreference = "Stop"
$url = "https://github.com/Microsoft/Git-Credential-Manager-for-Windows/releases/latest"
$asset = Invoke-WebRequest $url -UseBasicParsing
try {
$durl = (($asset.RawContent -split "`n" | ? { $_ -match '<a href="/.+\.exe"' }) -split '"')[1]
} catch {}
if ($durl) {
# Downloading Git Credential Manager
$url = "github.com" + $durl
$installer = "$env:temp\gitcredmanager.exe"
" - downloading"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest $url -OutFile $installer
$ProgressPreference = 'Continue'
# Installing Git Credential Manager
" - installing"
$install_args = "/VERYSILENT /SUPPRESSMSGBOXES /NOCANCEL /NORESTART /CLOSEAPPLICATIONS /RESTARTAPPLICATIONS"
Start-Process -FilePath $installer -ArgumentList $install_args -Wait
} else {
Write-Warning "Skipped!`nURL $url isn't accessible, install GIT Credential Manager for Windows manually"
_continue
}
}
function _installVSC {
# Test if Microsoft VS Code is already installed
$codeCmdPath = "$env:ProgramFiles\Microsoft VS Code\bin\code.cmd"
if ((Test-Path "$env:ProgramFiles\Microsoft VS Code\Code.exe") -or (Test-Path "$env:USERPROFILE\AppData\Local\Programs\Microsoft VS Code\Code.exe")) {
" - already installed"
return
}
# Downloading Microsoft VS Code
$vscInstaller = "$env:TEMP\vscode-stable.exe"
Remove-Item -Force $vscInstaller -ErrorAction SilentlyContinue
" - downloading"
$ProgressPreference = 'SilentlyContinue'
Invoke-WebRequest "https://update.code.visualstudio.com/latest/win32-x64/stable" -OutFile $vscInstaller
$ProgressPreference = 'Continue'
# Installing Microsoft VS Code
" - installing"
$loadInf = '@
[Setup]
Lang=english
Dir=C:\Program Files\Microsoft VS Code
Group=Visual Studio Code
NoIcons=0
Tasks=desktopicon,addcontextmenufiles,addcontextmenufolders,addtopath
@'
$infPath = Join-Path $env:TEMP load.inf
$loadInf | Out-File $infPath
Start-Process $vscInstaller -ArgumentList "/VERYSILENT /LOADINF=${infPath} /mergetasks=!runcode" -Wait
}
function _createSchedTask {
param ($xmlDefinition, $taskName)
$result = schtasks /CREATE /XML "$xmlDefinition" /TN "$taskName" /F
if (!$?) {
throw "Unable to create scheduled task $taskName"
}
}
function _startSchedTask {
param ($taskName)
$result = schtasks /RUN /I /TN "$taskName"
if (!$?) {
throw "Task $taskName finished with error. Check '$env:SystemRoot\temp\repo_sync.ps1.log'"
}
}
function _exportCred {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential] $credential
,
[string] $xmlPath = "$env:SystemDrive\temp\login.xml"
,
[Parameter(Mandatory = $true)]
[string] $runAs
)
begin {
# transform relative path to absolute
try {
$null = Split-Path $xmlPath -Qualifier -ErrorAction Stop
} catch {
$xmlPath = Join-Path (Get-Location) $xmlPath
}
# remove existing xml
Remove-Item $xmlPath -ErrorAction SilentlyContinue -Force
# create destination folder
[Void][System.IO.Directory]::CreateDirectory((Split-Path $xmlPath -Parent))
}
process {
$login = $credential.UserName
$pswd = $credential.GetNetworkCredential().password
$command = @"
# just in case auto-load of modules would be broken
import-module `$env:windir\System32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Security -ErrorAction Stop
`$pswd = ConvertTo-SecureString `'$pswd`' -AsPlainText -Force
`$credential = New-Object System.Management.Automation.PSCredential $login, `$pswd
Export-Clixml -inputObject `$credential -Path $xmlPath -Encoding UTF8 -Force -ErrorAction Stop
"@
# encode as base64
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedString = [Convert]::ToBase64String($bytes)
$A = New-ScheduledTaskAction -Argument "-executionpolicy bypass -noprofile -encodedcommand $encodedString" -Execute "$PSHome\powershell.exe"
if ($runAs -match "\$") {
# under gMSA account
$P = New-ScheduledTaskPrincipal -UserId $runAs -LogonType Password
} else {
# under system account
$P = New-ScheduledTaskPrincipal -UserId $runAs -LogonType ServiceAccount
}
$S = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
$taskName = "cred_export"
try {
$null = New-ScheduledTask -Action $A -Principal $P -Settings $S -ErrorAction Stop | Register-ScheduledTask -Force -TaskName $taskName -ErrorAction Stop
} catch {
if ($_ -match "No mapping between account names and security IDs was done") {
throw "Account $runAs doesn't exist or cannot be used on $env:COMPUTERNAME"
} else {
throw "Unable to create scheduled task for exporting credentials.`nError was:`n$_"
}
}
Start-Sleep -Seconds 1
Start-ScheduledTask $taskName
Start-Sleep -Seconds 5
$result = (Get-ScheduledTaskInfo $taskName).LastTaskResult
try {
Unregister-ScheduledTask $taskName -Confirm:$false -ErrorAction Stop
} catch {
throw "Unable to remove scheduled task $taskName. Remove it manually, it contains the credentials!"
}
if ($result -ne 0) {
throw "Export of the credentials end with error"
}
if ((Get-Item $xmlPath).Length -lt 500) {
# sometimes sched. task doesn't end with error, but xml contained gibberish
throw "Exported credentials are not valid"
}
}
}
function _isAdministrator {
$currentUser = [Security.Principal.WindowsPrincipal]([Security.Principal.WindowsIdentity]::GetCurrent())
Return $currentUser.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
#endregion helper functions
# store function definitions so I can recreate them in scriptblock
$allFunctionDefs = "function _continue { ${function:_continue} };function _pressKeyToContinue { ${function:_pressKeyToContinue} }; function _skip { ${function:_skip} }; function _installGIT { ${function:_installGIT} }; function _installGITCredManager { ${function:_installGITCredManager} }; function _createSchedTask { ${function:_createSchedTask} }; function _exportCred { ${function:_exportCred} }; function _startSchedTask { ${function:_startSchedTask} }; function _setPermissions { ${function:_setPermissions} }; function _getComputerMembership { ${function:_getComputerMembership} }; function _startProcess { ${function:_startProcess} }"
}
Process {
#region initial
if (!$noEnvModification) {
Clear-Host
@"
####################################
# INSTALL OPTIONS
####################################
1) TEST installation
- PURPOSE:
- Choose this option, if you want to make fast and safe (completely local) test of the features, this solution offers.
- REQUIREMENTS:
- Local Admin rights
- (HIGHLY RECOMMENDED) Run this installer on (freshly installed) VM with internet connectivity. Like Windows Sandbox, VirtualBox, Hyper-V, etc.
- WHAT IT DOES:
To have this as simple as possible - Installer automatically:
- Installs VSC, GIT.
- Creates GIT repository in "$remoteRepository".
- and clone it to "$env:SystemDrive\myCompanyRepository".
- Creates folder "$env:SystemDrive\repositoryShare" and shares it as "\\$env:COMPUTERNAME\repositoryShare".
- Creates local security groups repo_reader, repo_writer.
- Creates required scheduled tasks.
- Creates and sets global PowerShell profile.
- Starts VSC editor with your new repository, so you can start your testing immediately. :)
2) ACTIVE DIRECTORY installation
- PURPOSE:
- Choose this option, if you want to create fully featured CI/CD central GIT repository for your Active Directory environment.
- REQUIREMENTS:
- Active Directory
- Domain Admin rights
- Enabled PSRemoting
- Existing GIT Repository
- WHAT IT DOES:
- This script will set up your own GIT repository and your environment by:
- Creating repo_reader, repo_writer AD groups.
- Creates shared folder for serving repository data to the clients.
- Customizes generic data from repo_content_set_up folder to match your environment.
- Copies customized data to your repository.
- Sets up your repository:
- Activate custom git hooks.
- Set git user name and email.
- Commit & Push new content to your repository.
- Sets up MGM server:
- Copies the Repo_sync folder.
- Creates Repo_sync scheduled task.
- Exports repo_puller credentials.
- Copies exported credentials from MGM to local repository, Commmit and Push it.
- Creates a GPO '$GPOname' that will be used for connecting clients to this solution:
- NOTE: Linking GPO has to be done manually.
- NOTE: Every step has to be explicitly confirmed.
3) PERSONAL installation
- PURPOSE:
- Choose this option, if you want to leverage benefits of CI/CD for your personal PowerShell content or to share one GIT repository across multiple colleagues even without Active Directory.
- REQUIREMENTS:
- Local Admin rights
- Existing GIT repository
- WHAT IT DOES:
Installer automatically:
- Installs VSC, GIT (if necessary).
- Creates local security groups repo_reader, repo_writer.
- Let you decide what you want to synchronize from GIT:
- Global PowerShell profile
- Modules
- Custom section
- Creates required scheduled tasks.
- Repo_sync
- Pulls data from your GIT repository and process them
- will be run under your account therefore use your credentials to access GIT repository
- PS_env_set_up
- Synchronizes client with already processed repository data
- Starts VSC editor with your new repository, so you can start your testing immediately. :)
"@
# TODO
# 4) UPDATE of existing installation
# ! NO MODIFICATION OF YOUR ENVIRONMENT WILL BE MADE !
# - PURPOSE:
# - Choose this option if you want to deploy new version of this solution.
# - This option will just make customization of generic data in downloaded repo_content_set_up folder using data in your existing '$iniFile'.
# - Merging with your own repository etc has to be done manually.
# - REQUIREMENTS:
# - This solution is already deployed
$choice = ""
while ($choice -notmatch "^[1|2|3]$") {
$choice = Read-Host "Choose install option (1|2|3)"
}
# run again with admin rights if necessary
if ($choice -in 1, 3) {
if (!(_isAdministrator)) {
# not running "as Administrator" - so relaunch as administrator
# get command line arguments and reuse them
$arguments = $myInvocation.line -replace [regex]::Escape($myInvocation.InvocationName), ""
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" {1}' -f ($myinvocation.MyCommand.Definition), $arguments) # -noexit nebo -WindowStyle Hidden
# exit from the current, unelevated, process
exit
}
}
switch ($choice) {
1 {
$testInstallation = 1
$noEnvModification = $false
}
2 {
$ADInstallation = 1
$noEnvModification = $false
}
3 {
$personalInstallation = 1
$noEnvModification = $false
}
4 {
$updateRootData = 1
$noEnvModification = $true
}
default { throw "Undefined choice" }
}
}
Clear-Host
if ($personalInstallation -or $testInstallation) {
@"
####################################
# INSTALLING REQUIREMENTS
####################################
"@
" - installing 'GIT'"
_installGIT
" - installing 'VSC'"
_installVSC
" - installing 'Nuget'"
if (Get-PackageProvider -Name nuget -ListAvailable -ErrorAction SilentlyContinue | ? Version -GT '2.8.5') {
" - already installed"
} else {
Install-PackageProvider -Name nuget -Force -ForceBootstrap -Scope allusers | Out-Null
}
# solves issue https://github.com/PowerShell/vscode-powershell/issues/2824
" - installing 'PackageManagement' PS module"
if (Get-Module PackageManagement -ListAvailable | ? version -GT ([version]'1.4.8')) {
" - already installed"
} else {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-Module -Name PackageManagement -Force -ErrorAction SilentlyContinue
}
if ((Get-ExecutionPolicy -Scope LocalMachine) -notmatch "Bypass|RemoteSigned") {
# because of PS Global Profile loading
" - enabling running of PS scripts (because of PS Profile loading)"
Try {
Set-ExecutionPolicy RemoteSigned -Force -ErrorAction Stop
} Catch {
# this script being run with Bypass, so it is ok, that this command ends with error "Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope"
}
}
}
if (!$testInstallation) {
_pressKeyToContinue
Clear-Host
} else {
""
}
if (!$noEnvModification -and !$testInstallation) {
if ($personalInstallation) {
@"
####################################
# BEFORE YOU CONTINUE
####################################
- Create cloud or locally hosted GIT !private! repository (tested with Azure DevOps but probably will work also with GitHub etc).
- Clone this repository locally (git clone command).
- NOTE:
- More details can be found at https://github.com/ztrhgf/Powershell_CICD_repository/blob/master/1.%20HOW%20TO%20INSTALL.md
"@
} else {
@"
####################################
# BEFORE YOU CONTINUE
####################################
- Create cloud or locally hosted GIT !private! repository (tested with Azure DevOps but probably will work also with GitHub etc).
- Create READ only account in that repository (repo_puller).
- Create credentials for this account, that can be used in unattended way (i.e. alternate credentials in Azure DevOps).
- Clone this repository locally (git clone command).
- NOTE:
- More details can be found at https://github.com/ztrhgf/Powershell_CICD_repository/blob/master/1.%20HOW%20TO%20INSTALL.md
"@
}
_pressKeyToContinue
}
if (!$testInstallation) {
Clear-Host
} else {
""
}
if (!$noEnvModification -and !$testInstallation) {
@"
############################
!!! ANYONE WHO CONTROL THIS SOLUTION IS DE FACTO ADMINISTRATOR ON EVERY COMPUTER CONNECTED TO IT !!!
So:
- just approved users should have write access to GIT repository
- for accessing cloud GIT repository, use MFA if possible
$(if ($ADInstallation) {"- MGM server (processes repository data and uploads them to share) has to be protected so as the server that hosts that repository share"})
############################
"@
_pressKeyToContinue
Clear-Host
@"
############################
Your input will be stored to '$iniFile'. So next time you start this script, its content will be automatically used.
############################
"@
}
if (!$testInstallation) {
_pressKeyToContinue
Clear-Host
} else {
""
}
#endregion initial
try {
#region import variables
# import variables from ini file
# '#' can be used for comments, so skip such lines
if ((Test-Path $iniFile) -and !$testInstallation) {
Write-Host "- Importing variables from $iniFile" -ForegroundColor Green
Get-Content $iniFile -ErrorAction SilentlyContinue | ? { $_ -and $_ -notmatch "^\s*#" } | % {
$line = $_
if (($line -split $divider).count -ge 2) {
$position = $line.IndexOf($divider)
$name = $line.Substring(0, $position) -replace "^\s*|\s*$"
$value = $line.Substring($position + 1) -replace "^\s*|\s*$"
" - variable $name` will have value: $value"
# fill hash so I can later export (updated) variables back to file
$setupVariable.$name = $value
}
}
_pressKeyToContinue
}
#endregion import variables
if (!$testInstallation) {
Clear-Host
}
#region checks
if (!$updateRootData) {
Write-Host "- Checking permissions etc" -ForegroundColor Green
# # computer isn't in domain
# if (!$noEnvModification -and !(Get-WmiObject -Class win32_computersystem).partOfDomain) {
# Write-Warning "This PC isn't joined to domain. AD related steps will have to be done manually."
# ++$skipAD
# _continue
# }
# is local administrator
if (!(_isAdministrator)) {
Write-Warning "Not running as administrator. Symlink for using repository PowerShell snippets file in VSC won't be created"
++$notAdmin
_pressKeyToContinue
}
if ($ADInstallation) {
# is domain admin
if (!$noEnvModification -and !((& "$env:windir\system32\whoami.exe" /all) -match "Domain Admins|Enterprise Admins")) {
Write-Warning "You are not member of Domain nor Enterprise Admin group. AD related steps will have to be done manually."
++$notADAdmin
_continue
}
# ActiveDirectory PS module is available
if (!$noEnvModification -and !(Get-Module ActiveDirectory -ListAvailable)) {
Write-Warning "ActiveDirectory PowerShell module isn't installed (part of RSAT)."
if (!$notAdmin -and ((_continue "Proceed with installation" -passthru) -eq "Y")) {
if ($isServer) {
$null = Install-WindowsFeature -Name RSAT-AD-PowerShell -IncludeManagementTools
} else {
try {
$null = Get-WindowsCapability -Name "*activedirectory*" -Online -ErrorAction Stop | Add-WindowsCapability -Online -ErrorAction Stop
} catch {
Write-Warning "Unable to install RSAT AD tools.`nAD related steps will be skipped, so make them manually."
++$noADmodule
_pressKeyToContinue
}
}
} else {
Write-Warning "AD related steps will be skipped, so make them manually."
++$noADmodule
_pressKeyToContinue
}
}
# GroupPolicy PS module is available
if (!$noEnvModification -and !(Get-Module GroupPolicy -ListAvailable)) {
Write-Warning "GroupPolicy PowerShell module isn't installed (part of RSAT)."
if (!$notAdmin -and ((_continue "Proceed with installation" -passthru) -eq "Y")) {
if ($isServer) {
$null = Add-WindowsFeature -Name GPMC -IncludeManagementTools
} else {
try {
$null = Get-WindowsCapability -Name "*grouppolicy*" -Online -ErrorAction Stop | Add-WindowsCapability -Online -ErrorAction Stop
} catch {
Write-Warning "Unable to install RSAT GroupPolicy tools.`nGPO related steps will be skipped, so make them manually."
++$noGPOmodule
_pressKeyToContinue
}
}
} else {
Write-Warning "GPO related steps will be skipped, so make them manually."
++$noGPOmodule
_pressKeyToContinue
}
}
if ($notADAdmin -or $noADmodule) {
++$skipAD
}
if ($notADAdmin -or $noGPOmodule) {
++$skipGPO
}
}
if (!$testInstallation) {
_pressKeyToContinue
Clear-Host
}
}
#endregion checks
if ($ADInstallation -or $updateRootData) {
_setVariable MGMServer "the name of the MGM server (will be used for pulling, processing and distributing of repository data to repository share)."
if ($MGMServer -like "*.*") {
$MGMServer = ($MGMServer -split "\.")[0]
Write-Warning "$MGMServer was in FQDN format. Just hostname was used"
}
if ($ADInstallation -and !$noADmodule -and !(Get-ADComputer -Filter "name -eq '$MGMServer'")) {
throw "$MGMServer doesn't exist in AD"
}
} else {
if ($testInstallation) {
" - For testing purposes, this computer will host MGM server role too"
} elseif ($personalInstallation) {
" - For local installation, this computer will host MGM server role too"
}
_setVariableValue -variable MGMServer -value $env:COMPUTERNAME
}
if (!$testInstallation) {
_saveInput
Clear-Host
} else {
""
}
#region create repo_reader, repo_writer
if ($ADInstallation) {
Write-Host "- Creating repo_reader, repo_writer AD security groups" -ForegroundColor Green
if (!$noEnvModification -and !$skipAD -and !(_skip)) {
'repo_reader', 'repo_writer' | % {
if (Get-ADGroup -Filter "samaccountname -eq '$_'") {
" - $_ already exists"
} else {
if ($_ -match 'repo_reader') {
$right = "read"
} else {