forked from j81blog/GenLeCertForNS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenLeCertForNS.ps1
5635 lines (5323 loc) · 350 KB
/
GenLeCertForNS.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
Create a new or update an existing Let's Encrypt certificate for one or more domains and add it to a store then update the SSL bindings for a ADC
.DESCRIPTION
The script will utilize Posh-ACME to create a new or update an existing certificate for one or more domains. If generated successfully the script will add the certificate to the ADC and update the SSL binding for a web site. This script is for use with a Citrix ADC (v11.x and up). The script will validate the dns records provided. For example, the domain(s) listed must be configured with the same IP Address that is configured (via NAT) to a Content Switch. Or Use DNS verification if a WildCard domain was specified.
.PARAMETER Help
Display the detailed information about this script
.PARAMETER CleanADC
Clean-up the ADC configuration made within this script, for when somewhere it gone wrong
.PARAMETER RemoveTestCertificates
Remove all the Test/Staging certificates signed by the "Fake LE Intermediate X1" staging intermediate
.PARAMETER ManagementURL
Management URL, used to connect to the ADC
.PARAMETER Username
ADC Username with enough access to configure it
.PARAMETER Password
ADC Username password
.PARAMETER Credential
Use a PSCredential object instead of a Username or password. Use "Get-Credential" to generate a credential object
C:\PS> $Credential = Get-Credential
.PARAMETER CsVipName
Name of the HTTP ADC Content Switch used for the domain validation.
Specify only one when requesting a certificate
Specify all possible VIPs when creating a Command Policy (User group, -NSCPName), so they all can be used by the members
.PARAMETER UseLbVip
Skip the use of a Content Switch vServer (for example when using a GateWay Edition)\
Don't forget to specify a HTTP LB Vip Name, with the -LbVip parameter!
.PARAMETER LbName
ADC Load Balance VIP name
Default: "lb_letsencrypt_cert"
.PARAMETER CsVipBinding
ADC Content Switch binding used for the validation
Default: 11
.PARAMETER SvcName
ADC Load Balance service name
Default "svc_letsencrypt_cert_dummy"
.PARAMETER SvcDestination
IP Address used for the ADC Service (leave default 1.2.3.4, only change when already used
.PARAMETER RspName
ADC Responder Policy name
Default: "rsp_letsencrypt"
.PARAMETER RsaName
ADC Responder Action name
Default: "rsa_letsencrypt"
.PARAMETER CspName
ADC Content Switch Policy name
Default: "csp_NSCertCsp"
.PARAMETER CertKeyNameToUpdate
ADC SSL Certkey name currently in use, that needs to be renewed
.PARAMETER RemovePrevious
If the new certificate was updated successfully, remove the previous files.
This parameter works only if -CertKeyNameToUpdate was specified and previous files are found. Else this setting will be ignored!
.PARAMETER CertDir
Directory where to store the certificates
.PARAMETER PfxPassword
Specify a password for the PFX certificate, if not specified a new password is generated at the end
.PARAMETER KeyLength
Specify the KeyLength of the new to be generated certificate
Default: 2048
.PARAMETER EmailAddress
The email address used to request the certificates and receive a notification when the certificates (almost) expires
.PARAMETER CN
(Common Name) The Primary (first) dns record for the certificate
Example: "domain.com"
.PARAMETER SAN
(Subject Alternate Name) every following domain listed in this certificate. separated via an comma , and between quotes "".
Example: "sts.domain.com","www.domain.com","vpn.domain.com"
Example Wildcard: "*.domain.com","*.pub.domain.com"
NOTE: Only a DNS verification is possible when using WildCards!
.PARAMETER FriendlyName
The display name of the certificate, if not specified the CN will used. You can specify an empty value if required.
Example (Empty display name) : ""
Example (Set your own name) : "Custom Name"
.PARAMETER ValidationMethod
The validation method, this will be determined automatically. By default the 'http' validation method is being chosen unless you have defined a wildcard (*.domain.com) request.
Options: 'http' or 'dns'
.PARAMETER DNSPlugin
Refer to the Posh-ACME plugins for the parameters, https://github.com/rmbolger/Posh-ACME/tree/main/Posh-ACME/Plugins
Define the name with this parameter. You must also configure the 'DNSParams' parameter.
Example: -DNSPlugin 'Aurora'
.PARAMETER DNSParams
Define the Parameters required for the DNS plugin to be used with the 'DNSPlugin' parameter.
You can define the value as a hashtable: -DNSParams @{ Api='api.auroradns.eu'; Key='XXXXXXXXXX'; Secret='YYYYYYYYYYYYYYYY' }
Or as a string value (to be used in batch files): -DNSParams "Api=api.auroradns.eu;Key=XXXXXXXXXX;Secret=YYYYYYYYYYYYYYYY"
.PARAMETER Production
Use the production Let's encrypt server, without this parameter the staging (test) server will be used
.PARAMETER CreateUserPermissions
When this parameter is configured, a User Group (Command Policy) will be created with a limited set of permissions required to run this script.
Also specify all VIP, LB svc names if you want other than default values.
Mandatory parameter is the CsVipName.
.PARAMETER NSCPName
You can change the name of the Command Policy that will be created when you configure the -CreateUserPermissions parameter
Default: `"script-GenLeCertForNS`"
.PARAMETER CreateApiUser
When this parameter is configured, a (System) User will be created. This will me a member of the Command policy configured with -NSCPName
.PARAMETER ApiUsername
The Username for the (System) User
.PARAMETER ApiPassword
The Password for the (System) User
.PARAMETER DisableIPCheck
If you want to skip the IP Address verification, specify this parameter
.PARAMETER CleanPoshACMEStorage
Force cleanup of the Posh-Acme certificates located in "%LOCALAPPDATA%\Posh-ACME"
.PARAMETER ConfigFile
Use an existing or save all the "current" parameters to a json file of your choosing for later reuse of the same parameters.
.PARAMETER AutoRun
This parameter is used to make sure you are deliberately using the parameters from the config file and run the script automatically.
.PARAMETER ForceCertRenew
Specify this parameter if you want to renew certificate even though it's still valid.
.PARAMETER IPv6
If specified, the script will try run with IPv6 checks (EXPERIMENTAL)
.PARAMETER UpdateIIS
If specified, the script will try to add the generated certificate to the personal computer store and bind it to the site
.PARAMETER IISSiteToUpdate
Select a IIS Site you want to add the certificate to.
Default value when not specifying this parameter is "Default Web Site".
.PARAMETER PostPoSHScriptFilename
Configure this parameter with a full path name to a PowerShell script.
This script will be executed after a successful certificate request. The script needs three parameters:
1. [String]$Thumbprint => This will contain the thumbprint of the newly generated certificate
2. [String]$PFXfilename => This will contain the full path to the PFX certificate
3. [String]$PFXPassword => This will contain the PFX password
Return an exit code 0 for success or 1 if failed!
You can specify your own parameters (if needed) by specifying the "-PostPoSHScriptExtraParameters" parameter.
The GenLECertForNS script will continue even if the script failed! But it will generate an error message on the console or email.
.PARAMETER PostPoSHScriptExtraParameters
To be used together with the "-PostPoSHScriptFilename" parameter.
With this parameter you can pass your own parameters needed for the script (e.g. api credentials or a IIS Site name)
Specify as a hashtable
E.g. -PostPoSHScriptExtraParameters @{ IISSiteName="Default Web Site" }
.PARAMETER CleanExpiredCertsOnDisk
Files older than the days specified in the CleanExpiredCertsOnDiskDays parameter will be deleted in the in the -CertDir specified directory.
In an AutoRun configuration, you can specify a CertDir per request. This parameter will run per certificate request.
.PARAMETER CleanExpiredCertsOnDiskDays
Files older than the days specified will be deleted in the in the CertDir specified directory.
Default value: 100 days
.PARAMETER CleanAllExpiredCertsOnDisk
Files older than the days specified will be deleted in the in the CertDir specified directory.
This command can be used to only (manually) cleanup the in the CertDir specified directory.
.PARAMETER SendMail
Specify this parameter if you want to send a mail at the end, don't forget to specify SMTPTo, SMTPFrom, SMTPServer and if required SMTPCredential
.PARAMETER SMTPTo
Specify one or more email addresses.
Email addresses can be specified as "[email protected]" or "User Name <[email protected]>"
If specifying multiple email addresses, separate them wit a comma.
.PARAMETER SMTPFrom
Specify the Email address where mails are send from
The email address can be specified as "[email protected]" or "User Name <[email protected]>"
.PARAMETER SMTPServer
Specify the SMTP Mail server fqdn or IP-address
.PARAMETER SMTPPort
Specify the SMTP Mail server port
.PARAMETER SMTPUseSSL
Specify if the SMTP Mail server must use SSL
.PARAMETER SMTPCredential
Specify the Mail server credentials, only if credentials are required to send mails
.PARAMETER LogAsAttachment
If you specify this parameter, the log will be attached as attachment when sending the mail.
.PARAMETER DisableLogging
Turn off logging to logfile. Default ON
.PARAMETER LogLocation
Specify the log file name, default ".\GenLeCertForNS.txt"
.PARAMETER LogLevel
The Log level you want to have specified.
With LogLevel: Error; Only Error (E) data will be written or shown.
With LogLevel: Warning; Only Error (E) and Warning (W) data will be written or shown.
With LogLevel: Info; Only Error (E), Warning (W) and Info (I) data will be written or shown.
With LogLevel: Debug; All, Error (E), Warning (W), Info (I) and Debug (D) data will be written or shown.
You can also define a (Global) variable in your script $LogLevel, the function will use this level instead (if not specified with the command)
Default value: Info
.PARAMETER NoConsoleOutput
When Specified, no output will be written to the console.
Exception: Warning, Verbose and Error messages.
.EXAMPLE
.\GenLeCertForNS.ps1 -CreateUserPermissions -CreateApiUser -CsVipName "CSVIPNAME" -ApiUsername "le-user" -ApiPassword "LEP@ssw0rd" -NSCPName "MinLePermissionGroup" -Username nsroot -Password "nsroot" -ManagementURL https://citrixadc.domain.local
This command will create a Command Policy with the minimum set of permissions, you need to run this once to create (or when you want to change something).
Be sure to run the script next with the same parameters as specified when running this command, the same for -SvcName (Default "svc_letsencrypt_cert_dummy"), -LbName (Default: "lb_letsencrypt_cert"), -RspName (Default: "rsp_letsencrypt"), -RsaName (Default: "rsa_letsencrypt"), -CspName (Default: "csp_NSCertCsp")
Next time you want to generate certificates you can specify the new user -Username le-user -Password "LEP@ssw0rd"
.EXAMPLE
.\GenLeCertForNS.ps1 -CN "domain.com" -EmailAddress "[email protected]" -SAN "sts.domain.com","www.domain.com","vpn.domain.com" -PfxPassword "P@ssw0rd" -CertDir "C:\Certificates" -ManagementURL "http://192.168.100.1" -CsVipName "cs_domain.com_http" -Password "P@ssw0rd" -Username "nsroot" -CertKeyNameToUpdate "san_domain_com" -LogLevel Debug -Production
Generate a (Production) certificate for hostname "domain.com" with alternate names : "sts.domain.com, www.domain.com, vpn.domain.com". Using the email address "[email protected]". At the end storing the certificates in "C:\Certificates" and uploading them to the ADC. The Content Switch "cs_domain.com_http" will be used to validate the certificates.
.EXAMPLE
.\GenLeCertForNS.ps1 -CN "domain.com" -EmailAddress "[email protected]" -SAN "*.domain.com","*.test.domain.com" -PfxPassword "P@ssw0rd" -CertDir "C:\Certificates" -ManagementURL "http://192.168.100.1" -Password "P@ssw0rd" -Username "nsroot" -CertKeyNameToUpdate "wildcard_domain_com" -LogLevel Debug -Production
Generate a (Production) Wildcard (*) certificate for hostname "domain.com" with alternate names : "*.domain.com, *.test.domain.com. Using the email address "[email protected]". At the end storing the certificates in "C:\Certificates" and uploading them to the ADC.
NOTE: Only a DNS verification is possible when using WildCards!
.EXAMPLE
.\GenLeCertForNS.ps1 -CN "domain.com" -EmailAddress "[email protected]" -SAN "*.domain.com" -PfxPassword "P@ssw0rd" -CertDir "C:\Certificates" -ManagementURL "http://192.168.100.1" -Password "P@ssw0rd" -Username "nsroot" -CertKeyNameToUpdate "wildcard_domain_com" -DNSPlugin "Aurora" -DNSParams @{AuroraCredential=$((New-Object PSCredential 'KEYKEYKEY',$(ConvertTo-SecureString -String 'SECRETSECRETSECRET' -AsPlainText -Force))); AuroraApi='api.auroradns.eu'} -Production
Generate a (Production) Wildcard (*) certificate for hostname "domain.com" with alternate names : "*.domain.com, *.test.domain.com. Using the email address "[email protected]". At the end storing the certificates in "C:\Certificates" and uploading them to the ADC.
NOTE: Only a DNS verification is possible when using WildCards!
.EXAMPLE
.\GenLeCertForNS.ps1 -CleanADC -ManagementURL "http://192.168.100.1" -CsVipName "cs_domain.com_http" -Password "P@ssw0rd" -Username "nsroot"
Cleaning left over configuration from this script when something went wrong during a previous attempt to generate new certificates.
.EXAMPLE
.\GenLeCertForNS.ps1 -RemoveTestCertificates -ManagementURL "http://192.168.100.1" -Password "P@ssw0rd" -Username "nsroot"
Removing ALL the test certificates from your ADC.
.EXAMPLE
.\GenLeCertForNS.ps1 -RemoveTestCertificates -CleanAllExpiredCertsOnDisk -CertDir C:\Certificates -CleanExpiredCertsOnDiskDays 100
All subdirectories in "C:\Certificates" older than 100 days will be deleted.
.EXAMPLE
.\GenLeCertForNS.ps1 -AutoRun -ConfigFile ".\GenLe-Config.json"
Running the script with previously saved parameters. To create a test certificate.
NOTE: you can create the json file by specifying the -ConfigFile ".\GenLe-Config.json" parameter with your previous parameters
.EXAMPLE
.\GenLeCertForNS.ps1 -AutoRun -ConfigFile ".\GenLe-Config.json" -Production
Running the script with previously saved parameters. To create a Production (trusted) certificate
NOTE: you can create the json file by specifying the -ConfigFile ".\GenLe-Config.json" parameter with your previous parameters
.EXAMPLE
.\GenLeCertForNS.ps1 -CreateUserPermissions -NSCPName script-GenLeCertForNS -CreateApiUser -ApiUsername GenLEUser -ApiPassword P@ssw0rd! -ManagementURL https://citrixadc.domain.local -Username nsroot -Password nsr00t! -CsVipName cs_domain2.com_http,cs_domain2.com_http,cs_domain3.com_http
Create a Group (Command Policy) with limited user permissions required to run the script and a user that will be member of that group.
With all VIPs that can be used by the script.
.NOTES
File Name : GenLeCertForNS.ps1
Version : v2.15.0
Author : John Billekens
Requires : PowerShell v5.1 and up
ADC 12.1 and higher
Run As Administrator
Posh-ACME 4.17.0 (Will be installed via this script) Thank you @rmbolger for providing the HTTP validation method!
Microsoft .NET Framework 4.7.2 or later
.LINK
https://blog.j81.nl
#>
[CmdletBinding(DefaultParameterSetName = "LECertificatesHTTP")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingWriteHost", "")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingPlainTextForPassword", "")]
param(
[Parameter(ParameterSetName = "Help", Mandatory = $true)]
[alias("h")]
[Switch]$Help,
[Parameter(ParameterSetName = "CleanADC", Mandatory = $true)]
[alias("CleanNS")]
[Switch]$CleanADC,
[Parameter(ParameterSetName = "CleanTestCertificate", Mandatory = $true)]
[Switch]$RemoveTestCertificates,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[Switch]$CleanPoshACMEStorage,
[Parameter(ParameterSetName = "CommandPolicy", Mandatory = $true)]
[Parameter(ParameterSetName = "CommandPolicyUser", Mandatory = $true)]
[Parameter(ParameterSetName = "LECertificatesHTTP", Mandatory = $true)]
[Parameter(ParameterSetName = "LECertificatesDNS", Mandatory = $true)]
[Parameter(ParameterSetName = "CleanADC", Mandatory = $true)]
[Parameter(ParameterSetName = "CleanTestCertificate", Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[alias("URL", "NSManagementURL")]
[String]$ManagementURL,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[ValidateNotNullOrEmpty()]
[alias("User", "NSUsername", "ADCUsername")]
[String]$Username,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[ValidateNotNullOrEmpty()]
[ValidateScript( {
if ($_ -is [SecureString]) {
return $true
} elseif ($_ -is [String]) {
return $true
} else {
throw "You passed an unexpected object type for the credential (-Password)"
}
})][alias("NSPassword", "ADCPassword")]
[object]$Password,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[alias("NSCredential", "ADCCredential")]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]$Credential = [System.Management.Automation.PSCredential]::Empty,
[Parameter(ParameterSetName = "LECertificatesHTTP", Mandatory = $true)]
[Parameter(ParameterSetName = "LECertificatesDNS", Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$CN,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String[]]$SAN = @(),
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String]$FriendlyName,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[ValidateSet('http', 'dns', IgnoreCase = $true)]
[String]$ValidationMethod = "http",
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String]$DNSPlugin = "Manual",
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Object]$DNSParams = @{ },
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[alias("NSCertNameToUpdate")]
[ValidateLength(1, 31)]
[String]$CertKeyNameToUpdate,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$RemovePrevious,
[Parameter(ParameterSetName = "LECertificatesHTTP", Mandatory = $true)]
[Parameter(ParameterSetName = "LECertificatesDNS", Mandatory = $true)]
[Parameter(ParameterSetName = "CleanExpiredCerts", Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$CertDir,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[ValidateScript( {
if ($_ -is [SecureString]) {
return $true
} elseif ($_ -is [String]) {
return $true
} else {
throw "You passed an unexpected object type for the password (-PfxPassword). Must be (Secure)String"
}
})][object]$PfxPassword = $null,
[Parameter(ParameterSetName = "LECertificatesHTTP", Mandatory = $true)]
[Parameter(ParameterSetName = "LECertificatesDNS", Mandatory = $true)]
[String]$EmailAddress,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[ValidateScript( {
if ($_ -lt 2048 -Or $_ -gt 4096 -Or ($_ % 128) -ne 0) {
throw "Unsupported RSA key size. Must be 2048-4096 in 8 bit increments."
} else {
$true
}
})][int32]$KeyLength = 2048,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "AutoRun")]
[Switch]$Production,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[Switch]$DisableLogging,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[ValidateNotNullOrEmpty()]
[alias("LogLocation")]
[String]$LogFile = "<DEFAULT>",
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[Parameter(ParameterSetName = "CleanTestCertificate")]
[ValidateSet("Error", "Warning", "Info", "Debug", "None", IgnoreCase = $false)]
[String]$LogLevel = "Info",
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("SaveNSConfig")]
[Switch]$SaveADCConfig,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$SendMail,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String[]]$SMTPTo,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String]$SMTPFrom,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]$SMTPCredential = [System.Management.Automation.PSCredential]::Empty,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String]$SMTPServer,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Int]$SMTPPort = 25,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$SMTPUseSSL,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$LogAsAttachment,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$DisableIPCheck,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$IPv6,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$UpdateIIS,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String]$IISSiteToUpdate = "Default Web Site",
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[String]$PostPoSHScriptFilename,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Hashtable]$PostPoSHScriptExtraParameters = @{},
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSCsVipName")]
[String[]]$CsVipName,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$UseLbVip,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSCspName")]
[String]$CspName = "csp_letsencrypt",
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSCsVipBinding")]
[String]$CsVipBinding = 11,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSSvcName")]
[String]$SvcName = "svc_letsencrypt_cert_dummy",
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSSvcDestination")]
[String]$SvcDestination = "1.2.3.4",
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSLbName")]
[String]$LbName = "lb_letsencrypt_cert",
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("TD")]
[Int]$TrafficDomain = 0,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSRspName")]
[String]$RspName = "rsp_letsencrypt",
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "CleanADC")]
[alias("NSRsaName")]
[String]$RsaName = "rsa_letsencrypt",
[Parameter(ParameterSetName = "CommandPolicy", DontShow)]
[Parameter(ParameterSetName = "CommandPolicyUser", DontShow)]
[Parameter(ParameterSetName = "LECertificatesHTTP", DontShow)]
[Parameter(ParameterSetName = "LECertificatesDNS", DontShow)]
[Parameter(ParameterSetName = "CleanADC", DontShow)]
[String[]]$Partitions = @("default"),
[Parameter(ParameterSetName = "CommandPolicy", Mandatory = $true)]
[Parameter(ParameterSetName = "CommandPolicyUser", Mandatory = $true)]
[Switch]$CreateUserPermissions,
[Parameter(ParameterSetName = "CommandPolicy")]
[Parameter(ParameterSetName = "CommandPolicyUser")]
[String]$NSCPName = "script-GenLeCertForNS",
[Parameter(ParameterSetName = "CommandPolicyUser", Mandatory = $true)]
[Switch]$CreateApiUser,
[Parameter(ParameterSetName = "CommandPolicyUser", Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]$ApiUsername,
[Parameter(ParameterSetName = "CommandPolicyUser", Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[ValidateScript( {
if ($_ -is [SecureString]) {
return $true
} elseif ($_ -is [String]) {
return $true
} else {
throw "You passed an unexpected object type for the credential (-ApiPassword)"
}
})]
[object]$ApiPassword,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "AutoRun", Mandatory = $true)]
[String]$ConfigFile = $null,
[Parameter(ParameterSetName = "AutoRun", Mandatory = $true)]
[Switch]$AutoRun = $false,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Parameter(ParameterSetName = "AutoRun")]
[Alias('Force')]
[Switch]$ForceCertRenew = $false,
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[Switch]$CleanExpiredCertsOnDisk,
[Parameter(ParameterSetName = "CleanExpiredCerts", Mandatory = $true)]
[Switch]$CleanAllExpiredCertsOnDisk,
[Parameter(ParameterSetName = "CleanExpiredCerts")]
[Parameter(ParameterSetName = "LECertificatesHTTP")]
[Parameter(ParameterSetName = "LECertificatesDNS")]
[int16]$CleanExpiredCertsOnDiskDays = 100,
[Switch]$NoConsoleOutput
)
#requires -version 5.1
#Requires -RunAsAdministrator
$ScriptVersion = "2.15.0"
$PoshACMEVersion = "4.17.0"
$VersionURI = "https://drive.google.com/uc?export=download&id=1WOySj40yNHEza23b7eZ7wzWKymKv64JW"
#region Functions
function Write-ToLogFile {
<#
.SYNOPSIS
Write messages to a log file.
.DESCRIPTION
Write info to a log file.
.PARAMETER Message
The message you want to have written to the log file.
.PARAMETER Block
If you have a (large) block of data you want to have written without Date/Component tags, you can specify this parameter.
.PARAMETER E
Define the Message as an Error message.
.PARAMETER W
Define the Message as a Warning message.
.PARAMETER I
Define the Message as an Informational message.
Default value: This is the default value for all messages if not otherwise specified.
.PARAMETER D
Define the Message as a Debug Message
.PARAMETER Component
If you want to have a Component name in your log file, you can specify this parameter.
Default value: Name of calling script
.PARAMETER DateFormat
The date/time stamp used in the LogFile.
Default value: "yyyy-MM-dd HH:mm:ss:ffff"
.PARAMETER NoDate
If NoDate is defined, no date string will be added to the log file.
Default value: False
.PARAMETER Show
Show the Log Entry only to console.
.PARAMETER LogFile
The FileName of your log file.
You can also define a (Global) variable in your script $LogFile, the function will use this path instead (if not specified with the command).
Default value: <ScriptRoot>\Log.txt or if $PSScriptRoot is not available .\Log.txt
.PARAMETER Delimiter
Define your Custom Delimiter of the log file.
Default value: <TAB>
.PARAMETER LogLevel
The Log level you want to have specified.
With LogLevel: Error; Only Error (E) data will be written or shown.
With LogLevel: Warning; Only Error (E) and Warning (W) data will be written or shown.
With LogLevel: Info; Only Error (E), Warning (W) and Info (I) data will be written or shown.
With LogLevel: Debug; All, Error (E), Warning (W), Info (I) and Debug (D) data will be written or shown.
With LogLevel: None; Nothing will be written to disk or screen.
You can also define a (Global) variable in your script $LogLevel, the function will use this level instead (if not specified with the command)
Default value: Info
.PARAMETER NoLogHeader
Specify parameter if you don't want the log file to start with a header.
Default value: False
.PARAMETER WriteHeader
Only Write header with info to the log file.
.PARAMETER ExtraHeaderInfo
Specify a string with info you want to add to the log header.
.PARAMETER NewLog
Force to start a new log, previous log will be removed.
.EXAMPLE
Write-ToLogFile "This message will be written to a log file"
To write a message to a log file just specify the following command, it will be a default informational message.
.EXAMPLE
Write-ToLogFile -E "This message will be written to a log file"
To write a message to a log file just specify the following command, it will be a error message type.
.EXAMPLE
Write-ToLogFile "This message will be written to a log file" -NewLog
To start a new log file (previous log file will be removed)
.EXAMPLE
Write-ToLogFile "This message will be written to a log file"
If you have the variable $LogFile defined in your script, the Write-ToLogFile function will use that LofFile path to write to.
E.g. $LogFile = "C:\Path\LogFile.txt"
.NOTES
Function Name : Write-ToLogFile
Version : v0.2.6
Author : John Billekens
Requires : PowerShell v5.1 and up
.LINK
https://blog.j81.nl
#>
#requires -version 5.1
[CmdletBinding(DefaultParameterSetName = "Info")]
Param (
[Parameter(ParameterSetName = "Error", Mandatory = $true, Position = 0)]
[Parameter(ParameterSetName = "Warning", Mandatory = $true, Position = 0)]
[Parameter(ParameterSetName = "Info", Mandatory = $true, Position = 0)]
[Parameter(ParameterSetName = "Debug", Mandatory = $true, Position = 0)]
[ValidateNotNullOrEmpty()]
[Alias("M")]
[string[]]$Message,
[Parameter(ParameterSetName = "Block", Mandatory = $true)]
[Alias("B")]
[object[]]$Block,
[Parameter(ParameterSetName = "Block")]
[Alias("BI")]
[Switch]$BlockIndent,
[Parameter(ParameterSetName = "Error")]
[Switch]$E,
[Parameter(ParameterSetName = "Warning")]
[Switch]$W,
[Parameter(ParameterSetName = "Info")]
[Switch]$I,
[Parameter(ParameterSetName = "Block")]
[Parameter(ParameterSetName = "Debug")]
[Switch]$D,
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[Alias("C")]
[String]$Component = $(try { $(Split-Path -Path $($MyInvocation.ScriptName) -Leaf) } catch { "LOG" }),
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[Alias("ND")]
[Switch]$NoDate,
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[ValidateNotNullOrEmpty()]
[Alias("DF")]
[String]$DateFormat = "yyyy-MM-dd HH:mm:ss:ffff",
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[Parameter(ParameterSetName = "Block")]
[Alias("S")]
[Switch]$Show,
[String]$LogFile = "Log.txt",
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[String]$Delimiter = "`t",
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[Parameter(ParameterSetName = "Block")]
[ValidateSet("Error", "Warning", "Info", "Debug", "None", IgnoreCase = $false)]
[String]$LogLevel,
[Parameter(ParameterSetName = "Error")]
[Parameter(ParameterSetName = "Warning")]
[Parameter(ParameterSetName = "Info")]
[Parameter(ParameterSetName = "Debug")]
[Parameter(ParameterSetName = "Block")]
[Alias("NH", "NoHead")]
[Switch]$NoLogHeader,
[Parameter(ParameterSetName = "Head")]
[Alias("H", "Head")]
[Switch]$WriteHeader,
[Alias("HI")]
[String]$ExtraHeaderInfo = $null,
[Alias("NL")]
[Switch]$NewLog
)
$RootPath = $(if ($psISE) { Split-Path -Path $psISE.CurrentFile.FullPath } else { $(if ($global:PSScriptRoot.Length -gt 0) { $global:PSScriptRoot } else { $global:pwd.Path }) })
# Set Message Type to Informational if nothing is defined.
if ((-Not $I) -and (-Not $W) -and (-Not $E) -and (-Not $D) -and (-Not $Block) -and (-Not $WriteHeader)) {
$I = $true
}
#Check if a log file is defined in a Script. If defined, get value.
try {
$LogFileVar = Get-Variable -Scope Global -Name LogFile -ValueOnly -ErrorAction SilentlyContinue
if (-Not [String]::IsNullOrWhiteSpace($LogFileVar)) {
$LogFile = $LogFileVar
}
$LogFileVar = Get-Variable -Scope Script -Name LogFile -ValueOnly -ErrorAction SilentlyContinue
if (-Not [String]::IsNullOrWhiteSpace($LogFileVar)) {
$LogFile = $LogFileVar
}
} catch {
#Continue, no script variable found for LogFile
}
#Check if a LogLevel is defined in a script. If defined, get value.
try {
if ([String]::IsNullOrEmpty($LogLevel) -and (-Not $WriteHeader)) {
$LogLevelVar = Get-Variable -Scope Global -Name LogLevel -ValueOnly -ErrorAction Stop
$LogLevel = $LogLevelVar
}
} catch {
if ([String]::IsNullOrEmpty($LogLevel)) {
$LogLevel = "Info"
}
}
if (-Not ($LogLevel -eq "None")) {
#Check if LogFile parameter is empty
if ([String]::IsNullOrWhiteSpace($LogFile)) {
if (-Not $Show) {
Write-Warning "Messages not written to log file, LogFile path is empty!"
}
#Only Show Entries to Console
$Show = $true
} else {
#If Not Run in a Script "$PSScriptRoot" wil only contain "\" this will be changed to the current directory
$ParentPath = Split-Path -Path $LogFile -Parent -ErrorAction SilentlyContinue
if (([String]::IsNullOrEmpty($ParentPath)) -Or ($ParentPath -eq "\")) {
$LogFile = $(Join-Path -Path $RootPath -ChildPath $(Split-Path -Path $LogFile -Leaf))
}
}
Write-Verbose "LogFile: $LogFile"
#Define Log Header
if (-Not $Show) {
if (
(-Not ($NoLogHeader -eq $true) -and (-Not (Test-Path -Path $LogFile -ErrorAction SilentlyContinue))) -Or
(-Not ($NoLogHeader -eq $true) -and ($NewLog)) -Or
($WriteHeader)) {
$LogHeader = @"
**********************
LogFile: $LogFile
Start time: $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")
Username: $([Security.Principal.WindowsIdentity]::GetCurrent().Name)
RunAs Admin: $((New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
Machine: $($Env:COMPUTERNAME) ($([System.Environment]::OSVersion.VersionString))
PSCulture: $($PSCulture)
PSVersion: $($PSVersionTable.PSVersion)
PSEdition: $($PSVersionTable.PSEdition)
PSCompatibleVersions: $($PSVersionTable.PSCompatibleVersions -join ', ')
BuildVersion: $($PSVersionTable.BuildVersion)
PSCommandPath: $($PSCommandPath)
LanguageMode: $($ExecutionContext.SessionState.LanguageMode)
"@
if (-Not [String]::IsNullOrEmpty($ExtraHeaderInfo)) {
$LogHeader += "`r`n"
$LogHeader += $ExtraHeaderInfo.TrimEnd("`r`n")
}
$LogHeader += "`r`n`r`n**********************`r`n`r`n"
} else {
$LogHeader = $null
}
}
} else {
Write-Verbose "LogLevel is set to None!"
}
#Define date string to start log message with. If NoDate is defined no date string will be added to the log file.
if (-Not ($LogLevel -eq "None")) {
if (-Not ($NoDate) -and (-Not $Block) -and (-Not $WriteHeader)) {
$DateString = "{0}{1}" -f $(Get-Date -Format $DateFormat), $Delimiter
} else {
$DateString = $null
}
if (-Not [String]::IsNullOrEmpty($Component) -and (-Not $Block) -and (-Not $WriteHeader)) {
$Component = " {0}[{1}]{0}" -f $Delimiter, $Component.ToUpper()
} else {
$Component = "{0}{0}" -f $Delimiter
}
#Define the log sting for the Message Type
if ($Block -Or $WriteHeader) {
$WriteLog = $true
if ($D -and ($LogLevel -ne "Debug")) {
$WriteLog = $false
}
} elseif ($E -and (($LogLevel -eq "Error") -Or ($LogLevel -eq "Warning") -Or ($LogLevel -eq "Info") -Or ($LogLevel -eq "Debug"))) {
Write-Verbose -Message "LogType: [Error], LogLevel: [$LogLevel]"
$MessageType = "ERROR"
$WriteLog = $true
} elseif ($W -and (($LogLevel -eq "Warning") -Or ($LogLevel -eq "Info") -Or ($LogLevel -eq "Debug"))) {
Write-Verbose -Message "LogType: [Warning], LogLevel: [$LogLevel]"
$MessageType = "WARN "
$WriteLog = $true
} elseif ($I -and (($LogLevel -eq "Info") -Or ($LogLevel -eq "Debug"))) {
Write-Verbose -Message "LogType: [Info], LogLevel: [$LogLevel]"
$MessageType = "INFO "
$WriteLog = $true
} elseif ($D -and ($LogLevel -eq "Debug")) {
Write-Verbose -Message "LogType: [Debug], LogLevel: [$LogLevel]"
$MessageType = "DEBUG"
$WriteLog = $true
} else {
Write-Verbose -Message "No Log entry is made LogType: [Error: $E, Warning: $W, Info: $I, Debug: $D] LogLevel: [$LogLevel]"
$WriteLog = $false
}
} else {
$WriteLog = $false
}
#Write the line(s) of text to a file.
if ($WriteLog) {
if ($WriteHeader) {
$LogString = $LogHeader
} elseif ($Block) {
if ($BlockIndent) {
$BlockLineStart = "{0}{0}{0}" -f $Delimiter
} else {
$BlockLineStart = ""
}
if ($Block -is [System.String]) {
$LogString = "{0]{1}" -f $BlockLineStart, $Block.Replace("`r`n", "`r`n$BlockLineStart")
} else {
$LogString = "{0}{1}" -f $BlockLineStart, $($Block | Out-String).Replace("`r`n", "`r`n$BlockLineStart")
}
$LogString = "$($LogString.TrimEnd("$BlockLineStart").TrimEnd("`r`n"))`r`n"
} else {
$LogString = "{0}{1}{2}{3}" -f $DateString, $MessageType, $Component, $($Message | Out-String)
}
if ($Show) {
"$($LogString.TrimEnd("`r`n"))"
Write-Verbose -Message "Data shown in console, not written to file!"
} else {
if (($LogHeader) -and (-Not $WriteHeader)) {
$LogString = "{0}{1}" -f $LogHeader, $LogString
}
try {
if ($NewLog) {
try {
Remove-Item -Path $LogFile -Force -ErrorAction Stop
Write-Verbose -Message "Old log file removed"
} catch {
Write-Verbose -Message "Could not remove old log file, trying to append"
}
}
try {
[System.IO.File]::AppendAllText($LogFile, $LogString, [System.Text.Encoding]::Unicode)
Write-Verbose -Message "Data written to LogFile:`r`n `"$LogFile`""
} catch {
Write-Verbose -Message "Error while writing to log"
}
} catch {
#If file cannot be written, give an error
Write-Error -Category WriteError -Message "Could not write to file `"$LogFile`""
}
}
} else {
Write-Verbose -Message "Data not written to file!"
}
}
function Invoke-ADCRestApi {
<#
.SYNOPSIS
Invoke NetScaler NITRO REST API
.DESCRIPTION
Invoke NetScaler NITRO REST API
.PARAMETER Session
An existing custom NetScaler Web Request Session object returned by Connect-NetScaler
.PARAMETER Method
Specifies the method used for the web request
.PARAMETER Type
Type of the NS appliance resource
.PARAMETER Resource
Name of the NS appliance resource, optional
.PARAMETER Action
Name of the action to perform on the NS appliance resource
.PARAMETER Arguments
One or more arguments for the web request, in hashtable format
.PARAMETER Query
Specifies a query that can be send in the web request
.PARAMETER Filters
Specifies a filter that can be send to the remote server, in hashtable format
.PARAMETER Payload
Payload of the web request, in hashtable format
.PARAMETER GetWarning
Switch parameter, when turned on, warning message will be sent in 'message' field and 'WARNING' value is set in severity field of the response in case there is a warning.
Turned off by default
.PARAMETER OnErrorAction
Use this parameter to set the onerror status for nitro request. Applicable only for bulk requests.
Acceptable values: "EXIT", "CONTINUE", "ROLLBACK", default to "EXIT"
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[alias("ADCSession")]
[PSObject]$Session,
[Parameter(Mandatory = $true)]
[ValidateSet('DELETE', 'GET', 'POST', 'PUT')]
[String]$Method,
[Parameter(Mandatory = $true)]
[String]$Type,
[String]$Resource,
[String]$Action,
[hashtable]$Arguments = @{ },
[hashtable]$Query = @{ },
[Switch]$Stat = $false,
[ValidateScript( { $Method -eq 'GET' })]
[hashtable]$Filters = @{ },
[ValidateScript( { $Method -ne 'GET' })]