22 December 2023

Add a SAN to certificate request into additional attributes - SAN does not show in certificate

Hi, fellow certificate enthusiasts! Today I'm going to show you how to add a Subject Alternative Name (SAN) to a certificate request with certsrv and what you must do in certutil to make the CA accept the SAN. Let's get started.

First, you need to create a certificate request with certsrv. You can do this by opening a web browser and navigating to http://<your CA server>/certsrv. Then, click on "Request a certificate" and choose "advanced certificate request". On the next page, select "Submit a certificate request by using a base-64-encoded CMC or PKCS #10 file, or submit a renewal request by using a base-64-encoded PKCS #7 file". This option allows you to upload a certificate request file (.csr) that you have created with another tool, such as OpenSSL.

Now, here comes the fun part. To add a SAN to your request, you need to use the additional attributes field at the bottom of the page. This field allows you to specify any extra information that you want to include in your certificate request. To add a SAN, you need to use the following syntax:

san:dns=<your domain name>

For example, if you want to add a SAN for www.example.com, you would type:

san:dns=www.example.com

You can add multiple SANs by separating them with an ampersand ( & ) like this:

san:dns=www.example.com&dns=example.com

You can even add an ip address

san:dns=www.example.com&dns=example.com&ipaddress=10.0.0.15

Once you have entered your SANs, click on "Submit" and wait for your request to be processed.

But wait, there's more! You're not done yet. You see, by default, the CA will ignore any SANs that you have specified in your request. That's because the CA needs to be configured to accept SANs from certificate requests. To do that, you need to use certutil.

Certutil is a command-line tool that allows you to manage certificates and CAs. You can use it to enable SAN support on your CA by running the following command on your CA server:

certutil -setreg policy\EditFlags +EDITF_ATTRIBUTESUBJECTALTNAME2

This command will modify the registry value of EditFlags under the policy key of your CA configuration. It will add the flag EDITF_ATTRIBUTESUBJECTALTNAME2, which tells the CA to copy any SANs from the additional attributes field of the request to the certificate.

After running this command, you need to restart the CA service for the changes to take effect. You can do this by running:

net stop certsvc

net start certsvc

And that's it! You have successfully added a SAN to your certificate request with certsrv and enabled SAN support on your CA with certutil.



I hope you enjoyed this post and learned something new. If you have any questions or comments, feel free to leave them below.


17 October 2023

Download Exchange CU or SU and copy to all Exchange servers - Get-ExchangeCUandSUcopytoServers

Last update 13-10-2023 - V3.2


This is some sort of fork from the project started by Rune Moskvil Lyngås over at https://github.com/runely/PowerShell/tree/master/Get-ExchangeCU 
All credit goes to Rune Moskvil Lyngås.

My version of this module can be found here:
I will update the module when new CU's or SU's are published.

I adjusted the module he made and added the SU's (security update's) and the latest CU's including Exchange 2019.

Download the required Exchange CU or SU (security update) and copy to all your Exchange servers at once.

Run the module as follows: 
Import-Module yourpath\Get-ExchangeCUandSUcopytoServers.psm1 

Get-ExchangeCU -Version 2019_CU11_SU_JAN_2022 -Directory C$\Temp -Name server1,server2 -RemoveTemp


  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
<#
.Synopsis
   Download Cumulative Update or Security Update for Exchange 2013/2016/2019
.DESCRIPTION
   Download Cumulative Update or Security Update for Exchange 2013/2016/2019 to all or specified servers
   IMPORTANT: FIRST RUN THE FOLLOWING

   === Import-Module .\Get-ExchangeCUandSUcopytoServers.psm1 ===

.EXAMPLE
   Get-ExchangeCU -Version "2013_CUn" -Name Server1,Server2 -Directory "C$\Source" -RemoveTemp
   Download latest Cumulative Update for installed Exchange version (Exchange Management Shell required)
.EXAMPLE
   Get-MailboxServer | Get-ExchangeCU -Version "2013_CUnr"
   Download Cumulative Update to given Exchange servers at default location(\\Server\C$\Source).
.EXAMPLE
   Get-ExchangeCU -Version "2013_CUnr" -Name Server1,Server2
   Download Cumulative Update to given Exchange servers at default location(\\Server\C$\Source).
.EXAMPLE
   Get-MailboxServer | Get-ExchangeCU -Version "2013_CUnr" -Directory "C$\Source" -RemoveTemp
   Download Cumulative Update to given Exchange servers at specified location and remove temporary downloaded file
.EXAMPLE
    Get-ExchangeCU -Version 2019_CU11_SU_MAR_2022 -Directory C$\Temp -Name SERVERNAME1,SERVERNAME2 -RemoveTemp
    Download Cumulative Update to given Exchange servers at specified location and remove temporary downloaded file
   
.NOTES
   Author: Rune Moskvil Lyngås
   Additions: Edwin van Brenk
   Version history:
   3.2
		- Added url's for Exchange 2016 and 2019 Security updates october 2023 and the august security update's
   3.1
		- Added url's for Exchange 2016 and 2019 Security updates june 2023
   3.0
		- Added url for Exchange 2019 CU13
   2.9
		- Added url's for Exchange 2013,2016 and 2019 Security updates march 2023
   2.8
		- Added url's for Exchange 2013,2016 and 2019 Security updates february 2023
   2.7
		- Added url's for Exchange 2013,2016 and 2019 Security updates january 2023
   2.6
		- Added url's for Exchange 2013,2016 and 2019 Security updates november 2022
   2.5
		- Added url's for Exchange 2013,2016 and 2019 Security updates august 2022
   2.4
		- Minor adjustments
   2.3
		- Added url's for Exchange 2013,2016 and 2019 Security updates May 2022
   2.2
        - Added url's for Exchange 2016 CU23 and Exchange 2019 CU12
   2.1
		- Added url's for Exchange 2013,2016 and 2019 Security updates March 2022
   2.0
        - Added url's for Exchange 2013 CU23, Exchange 2016 CU13, CU14,CU15, CU16, CU17, CU18, CU19, CU20, CU21 and CU22, 
          Exchange 2019 CU9, CU10 and CU11, Exchange 2013,2016 and 2019 Security updates January 2022
   1.0.7
        - Added url for Exchange 2013 CU22, Exchange 2016 CU11 and CU12
   1.0.6
        - Added url for Exchange 2013 CU21 and Exchange 2016 CU10
   1.0.5
        - Added url for Exchange 2013 CU20 and Exchange 2016 CU9
   1.0.4
        - Added url for Exchange 2013 CU19 and Exchange 2016 CU8
        - Version parameter is no longer mandatory. If omitted, the latest CU for the installed Exchange version will be downloaded (requires Exchange Management Shell installed)
        - Name parameter is no longer mandatory. If omitted, CU will be downloaded to all Exchange servers (requires Exchange Management Shell installed)
   1.0.3
        - Added download urls into the module. No need to find them yourself anymore! Woho! :)
   1.0.2
        - Converted to a function. This makes it easier to import it through a powershell profile
   1.0.1
        - Fixed a bug where file would not be copied to all given servers when parameter $Name were given explicitly. This would not happen if names were pipelined in
        - Cleaned up the script a bit
        - More info are written to console
   1.0.0
        - Initial release
   
   Last updated: 24-05-2022
#>
Function Get-ExchangeCU
{
    [CmdletBinding(SupportsShouldProcess = $True)]
    Param(
        [Parameter(HelpMessage = "Exchange CU version to download")]
        [ValidateSet(
		# Exchange 2013
		"2013_CU22", `
		"2013_CU23", `
		"2013_CU23_SU_JAN_2022", `
		"2013_CU23_SU_MAR_2022", `
		"2013_CU23_SU_MAY_2022", `
		"2013_CU23_SU_AUG_2022", `
		"2013_CU23_SU_NOV_2022", `
		"2013_CU23_SU-19_JAN_2023", `
		"2013_CU23_SU-20_FEB_2023", `
		"2013_CU23_SU-21_MAR_2023", `
		# Exchange 2016
		"2016_CU11", `
		"2016_CU12", `
		"2016_CU13", `
		"2016_CU14", `
		"2016_CU15", `
		"2016_CU16", `
		"2016_CU17", `
		"2016_CU18", `
		"2016_CU19", `
		"2016_CU20", `
		"2016_CU21", `
		"2016_CU22", `
		"2016_CU23", `
		"2016_CU21_SU_JAN_2022", `
		"2016_CU22_SU_JAN_2022", `
		"2016_CU21_SU_MAR_2022", `
		"2016_CU22_SU_MAR_2022", `
		"2016_CU21_SU_MAY_2022", `
		"2016_CU22_SU_MAY_2022", `
		"2013_CU23_SU_MAY_2022", `
		"2016_CU22_SU_AUG_2022", `
		"2016_CU23_SU_AUG_2022", `
		"2016_CU22_SU_NOV_2022", `
		"2016_CU23_SU_NOV_2022", `
		"2016_CU23_SU-5_JAN_2023", `
		"2016_CU23_SU-6_FEB_2023",
		"2016_CU23_SU-7_MAR_2023", `
		"2016_CU23_SU-8_JUN_2023", `
		"2016_CU23_SU-9V2_AUG_2023", `
		"2016_CU23_SU-10_OCT_2023", `
		# Exchange 2019
		"2019_CU9", `
		"2019_CU10", `
		"2019_CU11", `
		"2019_CU12", `
		"2019_CU13", `
		"2019_CU10_SU_JAN_2022", `
		"2019_CU11_SU_JAN_2022", `
		"2019_CU10_SU_MAR_2022", `
		"2019_CU11_SU_MAR_2022", `
		"2019_CU10_SU_MAY_2022", `
		"2019_CU11_SU_MAY_2022", `
		"2019_CU11_SU_AUG_2022", `
		"2019_CU12_SU_AUG_2022", `
		"2019_CU11_SU_NOV_2022", `
		"2019_CU11_SU-9_JAN_2023", `
		"2019_CU11_SU-10_FEB_2023", `
		"2019_CU11_SU-11_MAR_2023", `
		"2019_CU12_SU_NOV_2022", `
		"2019_CU12_SU-5_JAN_2023", `
		"2019_CU12_SU-6_FEB_2023", `
		"2019_CU12_SU-7_MAR_2023", `
		"2019_CU12_SU-8_JUN_2023", `
		"2019_CU12_SU-9V2_AUG_2023", `
		"2019_CU12_SU-10_OCT_2023", `
		"2019_CU12_SU-10_OCT_2023", `
		"2019_CU13_SU-1_JUN_2023", `
		"2019_CU13_SU-2V2_AUG_2023", `
		"2019_CU13_SU-3_OCT_2023",
		)]
		
        [string]$Version,

        [Parameter(ValueFromPipelineByPropertyName = $True, HelpMessage = "Exchange servers. Given as an array: Server1,Server2")]
        [string[]]$Name,

        [Parameter(HelpMessage = "Download location on Exchange server. Given as an UNC path without the server name. Example: 'C$\Source' or 'Source'")]
        [ValidateNotNullOrEmpty()]
        [string]$Directory = "C$\Source",

        [Parameter(HelpMessage = "Give this switch to remove Cumulative Update from temp folder when script is done")]
        [switch]$RemoveTemp
    )

    begin
    {
        # if version is not set, choose the latest CU for the installed Exchange version
        if (!$Version)
        {
            # import Exchange Management Shell module and connect
            if (!(Get-Command "Get-ExchangeServer" -ErrorAction SilentlyContinue))
            {
                Write-Host "Exchange Management Shell is required to find installed Exchange version. Please start script in Exchange Management Shell or fill out Version parameter." -ForegroundColor Red
                break;
            }

            # get installed Exchange version
            $Servers = (Get-ExchangeServer | Select -ExpandProperty AdminDisplayVersion)

            # choose latest CU for installed Exchange version
            try
            {
                if ($Servers)
                {
                    if ($Servers.Count -gt 1)
                    {
                        if ($Servers[0].GetType().FullName -ne "Microsoft.Exchange.Data.ServerVersion")
                        {
                            Write-Host "Exchange Management Shell is required to find installed Exchange version. Please start script in Exchange Management Shell or fill out Version parameter." -ForegroundColor Red
                            break;
                        }

                        if ($Servers[0].Major -eq 15 -and $Servers[0].Minor -eq 0)
                        {
                            $Version = Get-ExchangeCUUri -Latest "2013"
                        }
                        elseif ($Servers[0].Major -eq 15 -and $Servers[0].Minor -eq 1)
                        {
                            $Version = Get-ExchangeCUUri -Latest "2016"
                        }
                    }
                    else
                    {
                        if ($Servers.GetType().FullName -ne "Microsoft.Exchange.Data.ServerVersion")
                        {
                            Write-Host "Exchange Management Shell is required to find installed Exchange version. Please start script in Exchange Management Shell or fill out Version parameter." -ForegroundColor Red
                            break;
                        }

                        if ($Servers.Major -eq 15 -and $Servers[0].Minor -eq 0)
                        {
                            $Version = Get-ExchangeCUUri -Latest "2013"
                        }
                        elseif ($Servers.Major -eq 15 -and $Servers[0].Minor -eq 1)
                        {
                            $Version = Get-ExchangeCUUri -Latest "2016"
                        }
                    }
                }
                else
                {
                    Write-Host "Command '(Get-ExchangeServer | Select -ExpandProperty AdminDisplayVersion)' did not return any results." -ForegroundColor Red
                    break;
                }
            }
            catch
            {
                Write-Host "Command '(Get-ExchangeServer | Select -ExpandProperty AdminDisplayVersion)' failed: ($_)" -ForegroundColor Red
                break;
            }
        }

        # get download link
        Write-Host "'$Version' - Getting download link : " -ForegroundColor Cyan -NoNewline
        [string]$Url = Get-ExchangeCUUri -Version $Version

        if ($Url -eq $null -or $Url -eq "" -or $Url.ToUpper() -eq "N/A")
        {
            Write-Host "Download link not available anymore. Please try a different version" -ForegroundColor Red
            break;
        }
        else
        {
            Write-Host "'$Url'" -ForegroundColor Green
        }

        # get filename of CU
        $FileName = Split-Path $Url -Leaf

        # create TempFile variable for CU
        $TempFile = $env:TEMP + "\$FileName"

        # download CU to $TempFile
        try
        {
            Write-Host "Downloading '$FileName' to '$TempFile' : " -ForegroundColor Cyan -NoNewline

            if (!(Test-Path $TempFile -ErrorAction Stop))
            {
                Start-BitsTransfer -Destination $TempFile -Source $Url -Description "Downloading $FileName to $TempFile" -ErrorAction Stop
                Write-Host "OK" -ForegroundColor Green
            }
            else
            {
                Write-Host "Already downloaded!" -ForegroundColor Green
            }
        }
        catch
        {
            Write-Host "Failed ($_)" -ForegroundColor Red
            break;
        }
    }

    process
    {
        # if not name is given, get all Exchange Servers
        if (!$Name)
        {
            # import Exchange Management Shell module and connect
            if (!(Get-Command "Get-ExchangeServer" -ErrorAction SilentlyContinue))
            {
                Write-Host "Exchange Management Shell is required to find installed Exchange servers. Please start script in Exchange Management Shell or fill out Version parameter." -ForegroundColor Red
                break;
            }

            # get installed Exchange servers
            $Name = (((Get-ExchangeServer | Select -ExpandProperty Name) -join ",") -split ",")
        }

        foreach ($Server in $Name)
        {
            $ServerPath = "\\$Server\$Directory"

            # make sure path exists on $Server
            try
            {
                Write-Host "Creating folder '$ServerPath' : " -ForegroundColor Cyan -NoNewline

                if (!(Test-Path $ServerPath -ErrorAction Stop))
                {
                    New-Item -Path $ServerPath -ItemType Directory | Out-Null
                    Write-Host "OK" -ForegroundColor Green
                }
                else
                {
                    Write-Host "Already exists." -ForegroundColor Green
                }
            }
            catch
            {
                Write-Host "Failed ($_)" -ForegroundColor Red
                continue;
            }
        
            # copy CU to server
            $ServerPath = "\\$Server\$Directory\$FileName"
            try
            {
                Write-Host "Copying '$FileName' to '$ServerPath' : " -ForegroundColor Cyan -NoNewline

                if (!(Test-Path $ServerPath -ErrorAction Stop))
                {
                    Copy-Item -Path $TempFile -Destination $ServerPath -Force
                    Write-Host "OK" -ForegroundColor Green
                }
                else
                {
                    Write-Host "Already exists." -ForegroundColor Green
                }
            }
            catch
            {
                Write-Host "Failed ($_)" -ForegroundColor Red

                if ($RemoveTemp)
                {
                    $PSBoundParameters.Remove('RemoveTemp') | Out-Null
                    Write-Host "RemoveTemp switch was removed due to an error with copying '$FileName' to '$ServerPath'" -ForegroundColor Yellow
                }
            }
        }
    }

    end
    {
        if ($RemoveTemp)
        {
            Write-Host "Removing temporary file '$TempFile' : " -ForegroundColor Cyan -NoNewline

            try
            {
                Remove-Item -Path $TempFile -Force -Confirm:$False
                Write-Host "OK" -ForegroundColor Green
            }
            catch
            {
                Write-Host "Failed ($_)" -ForegroundColor Red
            }
        }
    }
}

Function Get-ExchangeCUUri
{
    param(
        [Parameter(Mandatory = $True, ParameterSetName = "Version")]
        [string]$Version,

        [Parameter(Mandatory = $True, ParameterSetName = "Latest")]
        [ValidateSet("2013", "2016")]
        [string]$Latest
    )

    # Exchange version table
    $ExchangeTable = @()
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU1"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU2"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU3"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU4/SP1"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU5"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU6"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU7"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU8"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU9"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU10"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU11"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU12"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU13"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU14"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU15"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU16"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU17"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU18"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU19"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU20"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU21"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU22"; Value = "https://download.microsoft.com/download/7/9/8/7982ED00-C0F5-44BB-8B40-768951AE4CC7/Exchange2013-x64-cu22.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23"; Value = "https://download.microsoft.com/download/7/F/D/7FDCC96C-26C0-4D49-B5DB-5A8B36935903/Exchange2013-x64-cu23.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU_JAN_2022"; Value = "https://download.microsoft.com/download/b/a/f/baf576c9-f5d6-44e0-84c1-c97add5f627b/Exchange2013-KB5008631-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU_MAR_2022"; Value = "https://download.microsoft.com/download/8/2/9/829126b2-b532-4950-a125-49d50e2fda40/Exchange2013-KB5010324-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU_MAY_2022"; Value = "https://download.microsoft.com/download/e/2/4/e248e85e-12e8-4f22-9301-967afa639734/Exchange2013-KB5014260-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU_AUG_2022"; Value = "https://download.microsoft.com/download/b/d/4/bd4d3875-055b-4450-9ae7-ed34a0b051a8/Exchange2013-KB5015321-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU_NOV_2022"; Value = "https://download.microsoft.com/download/b/3/3/b33cf488-9f00-411f-8f08-beef7d219e81/Exchange2013-KB5019758-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU-19_JAN_2023"; Value = "https://download.microsoft.com/download/f/6/6/f667a13e-0894-4d3e-aa9a-b8f359075b9f/Exchange2013-KB5022188-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU-20_FEB_2023"; Value = "https://download.microsoft.com/download/8/0/8/80826d97-0515-406d-aa02-e78e714e2dda/Exchange2013-KB5023038-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2013_CU23_SU-21_MAR_2023"; Value = "https://download.microsoft.com/download/a/6/7/a6725875-28a0-4791-abd8-4608184f4451/Exchange2013-KB5024296-x64-en.exe" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU1"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU2"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU3"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU4"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU5"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU6"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU7"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU8"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU9"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU10"; Value = "N/A" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU11"; Value = "https://download.microsoft.com/download/6/6/F/66F70200-E2E8-4E73-88F9-A1F6E3E04650/ExchangeServer2016-x64-cu11.iso" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU12"; Value = "https://download.microsoft.com/download/2/5/8/258D30CF-CA4C-433A-A618-FB7E6BCC4EEE/ExchangeServer2016-x64-cu12.iso" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU13"; Value = "https://download.microsoft.com/download/5/9/6/59681DAE-AB62-4854-8DEC-CA25FFEFE3B3/ExchangeServer2016-x64-cu13.iso" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU14"; Value = "https://download.microsoft.com/download/f/4/e/f4e4b3a0-925b-4eff-8cc7-8b5932d75b49/ExchangeServer2016-x64-cu14.iso" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU15"; Value = "https://download.microsoft.com/download/5/6/6/566de1bf-336a-4662-841c-98ef4e2c30bf/ExchangeServer2016-x64-CU15.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU16"; Value = "https://download.microsoft.com/download/b/e/d/bed20ad6-a4cb-4a6c-b744-354b3fed6a98/ExchangeServer2016-x64-CU16.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU17"; Value = "https://download.microsoft.com/download/0/5/f/05fbbfff-8316-4d12-a59d-80b3c56e4d81/ExchangeServer2016-x64-cu17.iso" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU18"; Value = "https://download.microsoft.com/download/d/2/3/d23b113b-9634-4456-acba-1f7b0ce22b0e/ExchangeServer2016-x64-cu18.iso" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU19"; Value = "https://download.microsoft.com/download/a/8/4/a84c8458-c924-4e6d-a19b-be65848c0fe3/ExchangeServer2016-x64-CU19.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU20"; Value = "https://download.microsoft.com/download/0/b/7/0b702b8b-03ab-4553-9e2c-c73bb0c8535f/ExchangeServer2016-x64-CU20.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU21"; Value = "https://download.microsoft.com/download/7/d/5/7d5c319b-510b-4a2c-a77a-099c6f30ab54/ExchangeServer2016-x64-CU21.ISO" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU22"; Value = "https://download.microsoft.com/download/f/0/e/f0e65686-3761-4c9d-b8b2-9fb71a207b8d/ExchangeServer2016-x64-CU22.ISO" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23"; Value = "https://download.microsoft.com/download/8/d/2/8d2d01b4-5bbb-4726-87da-0e331bc2b76f/ExchangeServer2016-x64-CU23.ISO" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU21_SU_JAN_2022"; Value = "https://download.microsoft.com/download/a/a/a/aaa3b6bf-543e-49f9-9403-faf3a8afe5a9/Exchange2016-KB5008631-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU21_SU_MAR_2022"; Value = "https://download.microsoft.com/download/8/c/5/8c535577-35f0-4235-9680-86d4c4b99c9a/Exchange2016-KB5012698-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU21_SU_MAY_2022"; Value = "https://download.microsoft.com/download/5/f/e/5fefd2c9-3430-46dc-9db6-1ebc3474b630/Exchange2016-KB5014261-x64-en.exe" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU22_SU_JAN_2022"; Value = "https://download.microsoft.com/download/8/0/9/80947b03-7fd2-44fe-877f-7870f9bedfb8/Exchange2016-KB5008631-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU22_SU_MAR_2022"; Value = "https://download.microsoft.com/download/e/e/b/eeb1d582-c61a-4d21-8dba-e28b2a309636/Exchange2016-KB5012698-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU22_SU_MAY_2022"; Value = "https://download.microsoft.com/download/d/5/5/d555a327-bfdd-45f0-ba44-a40cc982aa18/Exchange2016-KB5014261-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU22_SU_AUG_2022"; Value = "https://download.microsoft.com/download/d/6/8/d68be4c9-cb1b-45b2-a9a3-4a03c52b05c0/Exchange2016-KB5015322-x64-en.exe" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU_AUG_2022"; Value = "https://download.microsoft.com/download/6/4/f/64f1b3a5-6e36-4123-b9da-3bd071940b0e/Exchange2016-KB5015322-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU22_SU_NOV_2022"; Value = "https://download.microsoft.com/download/d/4/9/d4993639-8642-4461-a109-79d9ab46bc68/Exchange2016-KB5019758-x64-en.exe" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU_NOV_2022"; Value = "https://download.microsoft.com/download/e/9/a/e9a07b3b-b440-44bb-8484-7ece339ffaf1/Exchange2016-KB5019758-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU-5_JAN_2023"; Value = "https://download.microsoft.com/download/5/3/9/539b126b-c5d6-47fc-a8d6-51a72637df5f/Exchange2016-KB5022143-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU-6_FEB_2023"; Value = "https://download.microsoft.com/download/8/e/4/8e46efe9-2958-4996-b81b-a3a7ff0a8010/Exchange2016-KB5023038-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU-7_MAR_2023"; Value = "https://download.microsoft.com/download/5/2/d/52db0525-54e8-41db-9b4d-146e23f4e3c0/Exchange2016-KB5024296-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU-8_JUN_2023"; Value = "https://download.microsoft.com/download/2/a/0/2a0da4e3-6bd0-4dc2-b15c-160e052d437e/Exchange2016-KB5025903-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU-9V2_AUG_2023"; Value = "https://download.microsoft.com/download/3/8/c/38c31212-75aa-47ca-a5c2-59430c81d92e/Exchange2016-KB5030524-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2016_CU23_SU-10_OCT_2023"; Value = "https://download.microsoft.com/download/1/e/c/1ec981fd-0c47-4571-b8a5-6c1f847559ce/Exchange2016-KB5030877-x64-en.exe" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU9"; Value = "https://download.microsoft.com/download/d/7/b/d7bcf78a-00d2-4a46-a3d2-7d506116bcd2/ExchangeServer2019-x64-CU9.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU10"; Value = "https://download.microsoft.com/download/7/3/f/73f75f9e-e7fd-4cb0-a2fc-405cbb800f2d/ExchangeServer2019-x64-CU10.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11"; Value = "https://download.microsoft.com/download/5/3/e/53e75dbd-ca33-496a-bd23-1d861feaa02a/ExchangeServer2019-x64-CU11.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12"; Value = "https://download.microsoft.com/download/b/c/7/bc766694-8398-4258-8e1e-ce4ddb9b3f7d/ExchangeServer2019-x64-CU12.ISO" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU13"; Value = "https://download.microsoft.com/download/7/5/f/75f4d77e-002c-419c-a03a-948e8eb019f2/ExchangeServer2019-x64-CU13.ISO" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU10_SU_JAN_2022"; Value = "https://download.microsoft.com/download/4/d/9/4d9bc4d8-d64b-4237-a39a-792e4907bfff/Exchange2019-KB5008631-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU10_SU_MAR_2022"; Value = "https://download.microsoft.com/download/1/2/0/120adb28-ceaf-49cc-8c39-1b1cd59feb4e/Exchange2019-KB5012698-x64-en.msp" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU_JAN_2022"; Value = "https://download.microsoft.com/download/e/6/4/e643edcb-923f-4a47-8948-5e088196fcd6/Exchange2019-KB5008631-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU_MAR_2022"; Value = "https://download.microsoft.com/download/2/3/c/23c3be04-96a9-4d0c-9198-62603559467f/Exchange2019-KB5012698-x64-en.msp" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU10_SU_MAY_2022"; Value = "https://download.microsoft.com/download/0/f/d/0fd79f2c-f7a5-4a60-bebe-0db804aeb816/Exchange2019-KB5014261-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU_MAY_2022"; Value = "https://download.microsoft.com/download/d/7/8/d78f35af-4d36-43ac-b66d-40e895e39fdb/Exchange2019-KB5014261-x64-en.exe" })
    $ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU_AUG_2022"; Value = "https://download.microsoft.com/download/c/f/3/cf38c014-e63e-4e6a-9e06-d28d4093f763/Exchange2019-KB5015322-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU_AUG_2022"; Value = "https://download.microsoft.com/download/8/0/4/80473b09-a81a-4816-9a79-56d5c5cc4b39/Exchange2019-KB5015322-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU_NOV_2022"; Value = "https://download.microsoft.com/download/3/5/a/35a6ba9d-d36b-482c-8ca1-81ef2a6f05a3/Exchange2019-KB5019758-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU-9_JAN_2023"; Value = "https://download.microsoft.com/download/4/4/4/4447cb74-ce40-45bd-ac3c-9cedc97077f7/Exchange2019-KB5022193-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU-10_FEB_2023"; Value = "https://download.microsoft.com/download/5/6/f/56fb2a33-439a-4dcc-b23c-440b8418fcac/Exchange2019-KB5023038-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU11_SU-11_MAR_2023"; Value = "https://download.microsoft.com/download/2/6/8/26890e39-b9fe-4644-8d62-fd4c9489aaf2/Exchange2019-KB5024296-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU_NOV_2022"; Value = "https://download.microsoft.com/download/d/b/9/db9ee80e-9c18-40d8-91f9-f2353dcf4f86/Exchange2019-KB5019758-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU-5_JAN_2023"; Value = "https://download.microsoft.com/download/d/f/a/dfa11017-6b59-46a8-8ce6-0ecb6e1036f9/Exchange2019-KB5022193-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU-6_FEB_2023"; Value = "https://download.microsoft.com/download/d/7/5/d7593b57-e832-4ee5-b18c-10a1453b0bd7/Exchange2019-KB5023038-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU-7_MAR_2023"; Value = "https://download.microsoft.com/download/4/7/d/47d4e3e5-b8b7-452f-b51e-65d94f5295cb/Exchange2019-KB5024296-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU13_SU-8_JUN_2023"; Value = "https://download.microsoft.com/download/6/5/6/656a9a86-2358-4583-a33f-60515caf861b/Exchange2019-KB5026261-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU-9V2_AUG_2023"; Value = "https://download.microsoft.com/download/c/1/a/c1a9a39f-8abd-4fa4-bd55-d872d958b3d0/Exchange2019-KB5030524-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU12_SU-10_OCT_2023"; Value = "https://download.microsoft.com/download/a/1/b/a1bc1cbf-8bd6-4192-af5c-20eddf58d5df/Exchange2019-KB5030877-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU13_SU-1_JUN_2023"; Value = "https://download.microsoft.com/download/f/f/3/ff345e39-12d0-474b-ad70-ca29f7693bee/Exchange2019-KB5026261-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU13_SU-2V2_AUG_2023"; Value = "https://download.microsoft.com/download/3/b/d/3bd41cd2-44b8-46b6-a235-89e15d55ed3c/Exchange2019-KB5030524-x64-en.exe" })
	$ExchangeTable += (New-Object PSObject -Property @{ Name = "2019_CU13_SU-3_OCT_2023"; Value = "https://download.microsoft.com/download/d/f/5/df52cdbb-256e-46c4-93ce-1aa3bb67f630/Exchange2019-KB5030877-x64-en.exe" })
	
    if ($Version)
    {
        $Uri = ($ExchangeTable | Where { $_.Name -eq $Version } | Select -ExpandProperty Value)
    }
    elseif ($Latest)
    {
        $Uri = ($ExchangeTable | Where { $_.Name -like "$Latest*" } | Select -Last 1 | Select -ExpandProperty Name)
    }

    if ($Uri)
    {
        return $Uri
    }
    else
    {
        return "N/A"
    }
}

25 August 2023

Set Log on as a Service, Batch job, log on locally and access through RDP with PowerShell - Set-UserRights

This is one of those things why I love the community, someone thinks of a use case for a script builds it and shares it with the world.

In this case it's a script by Blake Drumm, originally created by Bill Loytty.

It allows you to grant or deny some common access rights like:

"Log on as a batch job (SeBatchLogonRight)"
"Allow log on locally (SeInteractiveLogonRight)"
"Access this computer from the network (SeNetworkLogonRight)"
"Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)"
"Log on as a service (SeServiceLogonRight)"
"Deny log on as a batch job (SeDenyBatchLogonRight)"
"Deny log on locally (SeDenyInteractiveLogonRight)"
"Deny access to this computer from the network (SeDenyNetworkLogonRight)"
"Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)"
"Deny log on as a service (SeDenyServiceLogonRight)"

Head over to Blake Drumm's page ( https://blakedrumm.com/blog/set-and-check-user-rights-assignment ) to check out the full description, working, history and features of the script.
There are 2 versions of the script, 1 to set the rights and 1 to check the rights.

Below is the Set-UserRights.ps1 script:
  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
<#
    .Synopsis
        Add and Remove User Right(s) for defined user(s) and computer(s).
    
    .DESCRIPTION
        Add and Remove User Rights via Powershell.
    
    .PARAMETER AddRight
        You want to Add a user right.
    
    .Parameter ComputerName
        Defines the name of the computer where the user right should be granted. This can be multiple values, comma seperated.
        Default is the local computer on which the script is run.
    
    .PARAMETER RemoveRight
        You want to Remove a user right.
    
    .Parameter Username
        Defines the Username under which the service should run. This can be multiple values, comma seperated.
        Use the form: domain\Username.
        Default is the user under which the script is run.
    
    .PARAMETER UserRight
        Defines the User Right you want to set. This can be multiple values, comma seperated.
        Name of the right you want to add to: SeServiceLogonRight
        There is no default for this argument
        
        Some (but not all) of the Options you can use:
        "Log on as a batch job (SeBatchLogonRight)"
        "Allow log on locally (SeInteractiveLogonRight)"
        "Access this computer from the network (SeNetworkLogonRight)"
        "Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)"
        "Log on as a service (SeServiceLogonRight)"
        "Deny log on as a batch job (SeDenyBatchLogonRight)"
        "Deny log on locally (SeDenyInteractiveLogonRight)"
        "Deny access to this computer from the network (SeDenyNetworkLogonRight)"
        "Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)"
        "Deny log on as a service (SeDenyServiceLogonRight)"
    
    .Example
        Usage:
        Single Users
        
            Add User Right "Log on as a service" for CONTOSO\User:
            .\Set-UserRights.ps1 -AddRight -Username CONTOSO\User -UserRight SeServiceLogonRight
                        
            Add User Right "Log on as a batch job" for CONTOSO\User:
            .\Set-UserRights.ps1 -AddRight -Username CONTOSO\User -UserRight SeBatchLogonRight

            Remove User Right "Log on as a batch job" for CONTOSO\User:
            .\Set-UserRights.ps1 -RemoveRight -Username CONTOSO\User -UserRight SeBatchLogonRight
            
            Add User Right "Allow log on locally" for current user:
            .\Set-UserRights.ps1 -AddRight -UserRight SeInteractiveLogonRight

            Remove User Right "Allow log on locally" for current user:
            .\Set-UserRights.ps1 -RemoveRight -UserRight SeInteractiveLogonRight
        
        Multiple Users / Services / Computers
            Add User Right "Log on as a service" and "Log on as a batch job" for CONTOSO\User and run on, local machine and SQL.contoso.com:
            .\Set-UserRights.ps1 -AddRight -UserRight SeServiceLogonRight, SeBatchLogonRight -ComputerName $env:COMPUTERNAME, SQL.contoso.com -UserName CONTOSO\User1, CONTOSO\User2
    
    .Notes
        Original Creator: Bill Loytty (weloytty)
        Based on this script found here: https://github.com/weloytty/QuirkyPSFunctions/blob/ab4b02f9cc05505eee97d2f744f4c9c798143af1/Source/Users/Grant-LogOnAsService.ps1
        I modified to my own needs: https://github.com/blakedrumm/SCOM-Scripts-and-SQL/blob/master/Powershell/General%20Functions/Set-UserRights.ps1
        
        My blog post: https://blakedrumm.com/blog/set-and-check-user-rights-assignment/
        
        Author: Blake Drumm (blakedrumm@microsoft.com)
        First Created on: January 5th, 2022
        Last Modified on: April 23rd, 2022
#>
param
(
    [Parameter(Position = 0,
               HelpMessage = 'You want to Add a user right.')]
    [Alias('add')]
    [switch]$AddRight,
    [Parameter(Position = 1)]
    [Alias('computer')]
    [array]$ComputerName,
    [Parameter(Position = 2,
               HelpMessage = 'You want to Remove a user right.')]
    [switch]$RemoveRight,
    [Parameter(Position = 3)]
    [Alias('user')]
    [array]$Username,
    [Parameter(Mandatory = $false,
               Position = 4)]
    [ValidateSet('SeNetworkLogonRight', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeSystemtimePrivilege', 'SeCreatePagefilePrivilege', 'SeDebugPrivilege', 'SeRemoteShutdownPrivilege', 'SeAuditPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeLoadDriverPrivilege', 'SeBatchLogonRight', 'SeServiceLogonRight', 'SeInteractiveLogonRight', 'SeSecurityPrivilege', 'SeSystemEnvironmentPrivilege', 'SeProfileSingleProcessPrivilege', 'SeSystemProfilePrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeRestorePrivilege', 'SeShutdownPrivilege', 'SeTakeOwnershipPrivilege', 'SeDenyNetworkLogonRight', 'SeDenyInteractiveLogonRight', 'SeUndockPrivilege', 'SeManageVolumePrivilege', 'SeRemoteInteractiveLogonRight', 'SeImpersonatePrivilege', 'SeCreateGlobalPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeTimeZonePrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeDelegateSessionUserImpersonatePrivilege', 'SeMachineAccountPrivilege', 'SeTrustedCredManAccessPrivilege', 'SeTcbPrivilege', 'SeCreateTokenPrivilege', 'SeCreatePermanentPrivilege', 'SeDenyBatchLogonRight', 'SeDenyServiceLogonRight', 'SeDenyRemoteInteractiveLogonRight', 'SeEnableDelegationPrivilege', 'SeLockMemoryPrivilege', 'SeRelabelPrivilege', 'SeSyncAgentPrivilege', IgnoreCase = $true)]
    [Alias('right')]
    [array]$UserRight
)
BEGIN
{
    
    Write-Output '==================================================================='
    Write-Output '==========================  Start of Script ======================='
    Write-Output '==================================================================='
    
    $checkingpermission = "Checking for elevated permissions..."
    $scriptout += $checkingpermission
    Write-Output $checkingpermission
    if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
    {
        $currentPath = $myinvocation.mycommand.definition
        $nopermission = "Insufficient permissions to run this script. Attempting to open the PowerShell script ($currentPath) as administrator."
        $scriptout += $nopermission
        Write-Warning $nopermission
        # We are not running "as Administrator" - so relaunch as administrator
        # ($MyInvocation.Line -split '\.ps1[\s\''\"]\s*', 2)[-1]
        Start-Process powershell.exe "-File", ('"{0}"' -f $MyInvocation.MyCommand.Path) -Verb RunAs
        break
    }
    else
    {
        $permissiongranted = " Currently running as administrator - proceeding with script execution..."
        Write-Output $permissiongranted
    }
    
    Function Time-Stamp
    {
        $TimeStamp = Get-Date -UFormat "%B %d, %Y @ %r"
        return "$TimeStamp - "
    }
}
PROCESS
{
    function Inner-SetUserRights
    {
        param
        (
            [Parameter(Position = 0,
                       HelpMessage = 'You want to Add a user right.')]
            [Alias('add')]
            [switch]$AddRight,
            [Parameter(Position = 1)]
            [Alias('computer')]
            [array]$ComputerName,
            [Parameter(Position = 2,
                       HelpMessage = 'You want to Remove a user right.')]
            [switch]$RemoveRight,
            [Parameter(Position = 3)]
            [Alias('user')]
            [array]$Username,
            [Parameter(Mandatory = $false,
                       Position = 4)]
            [Alias('right')]
            [array]$UserRight
        )
        if (!$UserRight)
        {
            Write-Warning "Inner Function: Unable to continue because you did not supply the '-UserRight' parameter."
            break
        }
        if (!$AddRight -and !$RemoveRight)
        {
            Write-Warning "Inner Function: Unable to continue because you did not supply the '-AddRight' or '-RemoveRight' switches."
            break
        }
        elseif ($AddRight -and $RemoveRight)
        {
            Write-Warning "Inner Function: Unable to continue because you used both the '-AddRight' and '-RemoveRight' switches. Run again with just one of these present, either Add or Remove."
            break
        }
        elseif ($AddRight)
        {
            Write-Verbose "Inner Function: Detected -AddRight switch in execution."
            $ActionType = 'Adding'
        }
        elseif ($RemoveRight)
        {
            Write-Verbose "Inner Function: Detected -RemoveRight switch in execution."
            $ActionType = 'Removing'
        }
        else
        {
            Write-Warning "Something is wrong, detected logic is broken before executing main function. Exiting."
            break
        }
        Function Time-Stamp
        {
            $TimeStamp = Get-Date -UFormat "%B %d, %Y @ %r"
            return "$TimeStamp - "
        }
        $tempPath = [System.IO.Path]::GetTempPath()
        $import = Join-Path -Path $tempPath -ChildPath "import.inf"
        if (Test-Path $import) { Remove-Item -Path $import -Force }
        $export = Join-Path -Path $tempPath -ChildPath "export.inf"
        if (Test-Path $export) { Remove-Item -Path $export -Force }
        $secedt = Join-Path -Path $tempPath -ChildPath "secedt.sdb"
        if (Test-Path $secedt) { Remove-Item -Path $secedt -Force }
        $Error.Clear()
        try
        {
            foreach ($right in $UserRight)
            {
                $UserLogonRight = switch ($right)
                {
                    "SeBatchLogonRight"                 { "Log on as a batch job (SeBatchLogonRight)" }
                    "SeDenyBatchLogonRight"             { "Deny log on as a batch job (SeDenyBatchLogonRight)" }
                    "SeDenyInteractiveLogonRight"       { "Deny log on locally (SeDenyInteractiveLogonRight)" }
                    "SeDenyNetworkLogonRight"           { "Deny access to this computer from the network (SeDenyNetworkLogonRight)" }
                    "SeDenyRemoteInteractiveLogonRight" { "Deny log on through Remote Desktop Services (SeDenyRemoteInteractiveLogonRight)" }
                    "SeDenyServiceLogonRight"           { "Deny log on as a service (SeDenyServiceLogonRight)" }
                    "SeInteractiveLogonRight"           { "Allow log on locally (SeInteractiveLogonRight)" }
                    "SeNetworkLogonRight"               { "Access this computer from the network (SeNetworkLogonRight)" }
                    "SeRemoteInteractiveLogonRight"     { "Allow log on through Remote Desktop Services (SeRemoteInteractiveLogonRight)" }
                    "SeServiceLogonRight"               { "Log on as a service (SeServiceLogonRight)" }
                    Default                             { "($right)" }
                }
                Write-Output ("$(Time-Stamp)$ActionType `"$UserLogonRight`" right for user account: '$Username' on host: '$env:COMPUTERNAME'")
                if ($Username -match "^S-.*-.*-.*$|^S-.*-.*-.*-.*-.*-.*$|^S-.*-.*-.*-.*-.*$|^S-.*-.*-.*-.*$")
                {
                    $sid = $Username
                }
                else
                {
                    $sid = ((New-Object System.Security.Principal.NTAccount($Username)).Translate([System.Security.Principal.SecurityIdentifier])).Value
                }
                secedit /export /cfg $export | Out-Null
                #Change the below to any right you would like
                $sids = (Select-String $export -Pattern "$right").Line
                if ($ActionType -eq 'Adding')
                {
                    $sidList = "$sids,*$sid"
                }
                elseif ($ActionType -eq 'Removing')
                {
                    $sidList = "$($sids.Replace("*$sid", '').Replace("$Username", '').Replace(",,", ',').Replace("= ,", '= '))"
                }
                foreach ($line in @("[Unicode]", "Unicode=yes", "[System Access]", "[Event Audit]", "[Registry Values]", "[Version]", "signature=`"`$CHICAGO$`"", "Revision=1", "[Profile Description]", "Description=$ActionType `"$UserLogonRight`" right for user account: $Username", "[Privilege Rights]", "$sidList"))
                {
                    Add-Content $import $line
                }
            }
            
            secedit /import /db $secedt /cfg $import | Out-Null
            secedit /configure /db $secedt | Out-Null
            gpupdate /force | Out-Null
            Write-Verbose "The script will not delete the following paths due to running in verbose mode, please remove these files manually if needed:"
            Write-Verbose "`$import : $import"
            Write-Verbose "`$export : $export"
            Write-Verbose "`$secedt : $secedt"
            
            if ($VerbosePreference.value__ -eq 0)
            {
                Remove-Item -Path $import -Force | Out-Null
                Remove-Item -Path $export -Force | Out-Null
                Remove-Item -Path $secedt -Force | Out-Null
            }
        }
        catch
        {
            Write-Output ("$(Time-Stamp)Failure occurred while granting `"$right`" to user account: '$Username' on host: '$env:COMPUTERNAME'")
            Write-Output "Error Details: $error"
        }
    }
    $InnerSetUserRightFunctionScript = "function Inner-SetUserRights { ${function:Inner-SetUserRights} }"
    function Set-UserRights
    {
        param
        (
            [Parameter(Position = 0,
                       HelpMessage = 'You want to Add a user right.')]
            [Alias('add')]
            [switch]$AddRight,
            [Parameter(Position = 1)]
            [Alias('computer')]
            [array]$ComputerName,
            [Parameter(Position = 2,
                       HelpMessage = 'You want to Remove a user right.')]
            [switch]$RemoveRight,
            [Parameter(Position = 3)]
            [Alias('user')]
            [array]$Username,
            [Parameter(Mandatory = $false,
                       Position = 4)]
            [ValidateSet('SeNetworkLogonRight', 'SeBackupPrivilege', 'SeChangeNotifyPrivilege', 'SeSystemtimePrivilege', 'SeCreatePagefilePrivilege', 'SeDebugPrivilege', 'SeRemoteShutdownPrivilege', 'SeAuditPrivilege', 'SeIncreaseQuotaPrivilege', 'SeIncreaseBasePriorityPrivilege', 'SeLoadDriverPrivilege', 'SeBatchLogonRight', 'SeServiceLogonRight', 'SeInteractiveLogonRight', 'SeSecurityPrivilege', 'SeSystemEnvironmentPrivilege', 'SeProfileSingleProcessPrivilege', 'SeSystemProfilePrivilege', 'SeAssignPrimaryTokenPrivilege', 'SeRestorePrivilege', 'SeShutdownPrivilege', 'SeTakeOwnershipPrivilege', 'SeDenyNetworkLogonRight', 'SeDenyInteractiveLogonRight', 'SeUndockPrivilege', 'SeManageVolumePrivilege', 'SeRemoteInteractiveLogonRight', 'SeImpersonatePrivilege', 'SeCreateGlobalPrivilege', 'SeIncreaseWorkingSetPrivilege', 'SeTimeZonePrivilege', 'SeCreateSymbolicLinkPrivilege', 'SeDelegateSessionUserImpersonatePrivilege', 'SeMachineAccountPrivilege', 'SeTrustedCredManAccessPrivilege', 'SeTcbPrivilege', 'SeCreateTokenPrivilege', 'SeCreatePermanentPrivilege', 'SeDenyBatchLogonRight', 'SeDenyServiceLogonRight', 'SeDenyRemoteInteractiveLogonRight', 'SeEnableDelegationPrivilege', 'SeLockMemoryPrivilege', 'SeRelabelPrivilege', 'SeSyncAgentPrivilege', IgnoreCase = $true)]
            [Alias('right')]
            [array]$UserRight
        )
        if (!$Username)
        {
            $Username = "$env:USERDOMAIN`\$env:USERNAME"
        }
        if (!$UserRight)
        {
            Write-Warning "Main Function: Unable to continue because you did not supply the '-UserRight' parameter."
            break
        }
        if (!$AddRight -and !$RemoveRight)
        {
            Write-Warning "Main Function: Unable to continue because you did not supply the '-AddRight' or '-RemoveRight' switches."
            break
        }
        elseif ($AddRight -and $RemoveRight)
        {
            Write-Warning "Main Function: Unable to continue because you used both the '-AddRight' and '-RemoveRight' switches. Run again with just one of these present, either Add or Remove."
            break
        }
        elseif ($AddRight)
        {
            Write-Verbose "Main Function: Detected -AddRight switch in execution."
            $ActionType = 'Adding'
        }
        elseif ($RemoveRight)
        {
            Write-Verbose "Main Function: Detected -RemoveRight switch in execution."
            $ActionType = 'Removing'
        }
        if (!$ComputerName)
        {
            $ComputerName = $env:ComputerName
        }
        foreach ($user in $Username)
        {
            foreach ($right in $UserRight)
            {
                foreach ($computer in $ComputerName)
                {
                    if ($computer -match $env:COMPUTERNAME)
                    {
                        Inner-SetUserRights -UserRight $right -Username $user -AddRight:$AddRight -RemoveRight:$RemoveRight
                    }
                    else
                    {
                        Invoke-Command -ComputerName $Computer -Script {
                            param ($script,
                                [string]$Username,
                                [Parameter(Mandatory = $true)]
                                [array]$UserRight,
                                $AddRight,
                                $RemoveRight,
                                $VerbosePreference)
                            . ([ScriptBlock]::Create($script))
                            $VerbosePreference = $VerbosePreference
                            $Error.Clear()
                            try
                            {
                                if ($VerbosePreference -eq 0)
                                {
                                    Inner-SetUserRights -Username $Username -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight
                                }
                                else
                                {
                                    Inner-SetUserRights -Username $Username -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight -Verbose
                                }
                            }
                            catch
                            {
                                $info = [PSCustomObject]@{
                                    Exception = $Error.Exception.Message
                                    Reason    = $Error.CategoryInfo.Reason
                                    Target    = $Error.CategoryInfo.TargetName
                                    Script    = $Error.InvocationInfo.ScriptName
                                    Line      = $Error.InvocationInfo.ScriptLineNumber
                                    Column    = $Error.InvocationInfo.OffsetInLine
                                    Date      = Get-Date
                                    User      = $env:username
                                }
                                Write-Warning "$info"
                            }
                            
                        } -ArgumentList $InnerSetUserRightFunctionScript, $user, $right, $AddRight, $RemoveRight, $VerbosePreference
                    }
                }
            }
        }
        
    }
    if ($ComputerName -or $Username -or $UserRight -or $RemoveRight)
    {
        foreach ($user in $Username)
        {
            Set-UserRights -ComputerName $ComputerName -Username $user -UserRight $UserRight -AddRight:$AddRight -RemoveRight:$RemoveRight
        }
    }
    else
    {
        
     <# Edit line 392 to modify the default command run when this script is executed.
       Example: 
            Set-UserRights -AddRight -UserRight SeServiceLogonRight, SeBatchLogonRight -ComputerName $env:COMPUTERNAME, SQL.contoso.com -UserName CONTOSO\User1, CONTOSO\User2
            or
            Set-UserRights -AddRight -UserRight SeBatchLogonRight -Username S-1-5-11
            or
            Set-UserRights -RemoveRight -UserRight SeBatchLogonRight -Username CONTOSO\User2
            or
            Set-UserRights -RemoveRight -UserRight SeServiceLogonRight, SeBatchLogonRight -Username CONTOSO\User1
       #>
        Set-UserRights
    }
}
END
{
    Write-Output "$(Time-Stamp)Script Completed!"
}