OneLoginApi.psm1

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
Function Add-OneLoginApiEventLogSource {
    <#
        .DESCRIPTION
            Adds an Event Log source, for script/module logging. Adding an Event Log source requires administrative rights.
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 19 April 2017
                - Initial release.
            V1.0.0.1 date: 1 May 2017
                - Minor updates to status handling.
            V1.0.0.2 date: 4 May 2017
                - Added additional return value.
            V1.0.0.3 date: 22 May 2017
                - Changed output to reduce the number of "Write-Host" messages.
            V1.0.0.4 date: 21 June 2017
                - Fixed typo.
                - Significantly improved performance.
                - Changed logging.
            V1.0.0.5 date: 21 June 2017
                - Added a return value if the event log source exists.
            V1.0.0.6 date: 28 June 2017
                - Added [CmdletBinding()].
            V1.0.0.7 date: 28 June 2017
                - Added a check for the source, then a check on the status of the query.
            V1.0.0.8 date: 13 March 2018
                - Updated whitespace.
                - Updated output to only output status on 'verbose'.
            V1.0.0.9 date: 23 August 2019
        .PARAMETER EventLogSource
            Mandatory parameter. This parameter is used to specify the event source, that script/modules will use for logging.
    #>

    [CmdletBinding()]
    Param (
        [Parameter(Mandatory = $True)]
        $EventLogSource
    )

    $message = ("{0}: Beginning {1}." -f [datetime]::Now, $MyInvocation.MyCommand)
    If ($PSBoundParameters['Verbose']) { Write-Verbose $message }

    # Check if $EventLogSource exists as a source. If the shell is not elevated and the check fails to access the Security log, assume the source does not exist.
    Try {
        $sourceExists = [System.Diagnostics.EventLog]::SourceExists("$EventLogSource")
    }
    Catch {
        $sourceExists = $False
    }

    If ($sourceExists -eq $False) {
        $message = ("{0}: The event source `"{1}`" does not exist. Prompting for elevation." -f [datetime]::Now, $EventLogSource)
        Write-Host $message -ForegroundColor White

        Try {
            Start-Process PowerShell -Verb RunAs -ArgumentList "New-EventLog -LogName Application -Source $EventLogSource -ErrorAction Stop"
        }
        Catch [System.InvalidOperationException] {
            $message = ("{0}: It appears that the user cancelled the operation." -f [datetime]::Now)
            Write-Host $message -ForegroundColor Yellow
            Return "Error"
        }
        Catch {
            $message = ("{0}: Unexpected error launching an elevated Powershell session. The specific error is: {1}" -f [datetime]::Now, $_.Exception.Message)
            Write-Host $message -ForegroundColor Red
            Return "Error"
        }

        Return "Success"
    }
    Else {
        $message = ("{0}: The event source `"{1}`" already exists. There is no action for {2} to take." -f [datetime]::Now, $EventLogSource, $MyInvocation.MyCommand)
        Write-Verbose $message

        Return "Success"
    }
} #1.0.0.9
Function Get-OneLoginApiEvent {
    <#
        .DESCRIPTION
            Accept various filters and returns matching events.
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 31 August 2021
                - Initial release
        .LINK
            https://github.com/wetling23/Public.OneLoginApi.PowerShellModule
        .PARAMETER AccessToken
            Represents a valid (not expired), secure string OneLogin OATH token (https://developers.onelogin.com/api-docs/2/oauth20-tokens/generate-tokens-2).
        .PARAMETER Username
            Represents a OneLogin user name, for which to return matching events. When excluded, events for all users will be returned.
        .PARAMETER UserId
            Represents a OneLogin user ID, for which to return matching events. When excluded, events for all users will be returned.
        .PARAMETER EventTypeId
            Event type ID, for which to search. When ommitted, all events are returned. Only a single event type ID is allowed per call. For a list of event type IDs, see https://developers.onelogin.com/api-docs/1/events/event-resource.
        .PARAMETER Since
            Date/time, representing the beginning of the search period. When ommitted, events will be returned, back to the maximuim retention date.
        .PARAMETER Until
            Date/time, representing the end of the search period. When ommitted, events will be returned to the current date/time.
        .PARAMETER ClientId
            Represents the ID of the desired OneLogin client.
        .PARAMETER DirectoryId
            Represents the ID of the desired OneLogin directory.
        .PARAMETER EventId
            Represents the ID of the a specific OneLogin event.
        .PARAMETER Resolution
            Represents the value of the desired event resolution.
        .PARAMETER EventLogSource
            When included, (and when LogPath is null), represents the event log source for the Application log. If no event log source or path are provided, output is sent only to the host.
        .PARAMETER LogPath
            When included (when EventLogSource is null), represents the file, to which the cmdlet will output will be logged. If no path or event log source are provided, output is sent only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token>
 
            In this example, the command will return the maximum number of OneLogin events. Limited output logging will be written only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token> -Username user@domain.com -Since 01-01-2020 -Until 01-02-2020T20:00Z -Verbose
 
            In this example, the command will return all OneLogin events for user@domain.com, which occurred between 01-01-2020 and 01-02-2020 at 20:00 Zulu. Verbose output logging will be written only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token> -UserId 12345 -Since 01-01-2020 -LogPath C:\Temp\log.txt
 
            In this example, the command will return all OneLogin events for the user with ID 12345, which occurred between 01-01-2020 and the current date. Limited output logging will be written to the host and C:\Temp\log.txt.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [securestring]$AccessToken,

        [string]$Username,

        [int]$EventTypeId,

        [datetime]$Since,

        [datetime]$Until,

        [int]$UserId,

        [int]$ClientId,

        [int]$DirectoryId,

        [int]$EventId,

        [string]$Resolution,

        [string]$EventLogSource,

        [string]$LogPath
    )

    $message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $MyInvocation.MyCommand)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    #region Setup
    # Initialize variables.
    $events = [System.Collections.Generic.List[PSObject]]::new()
    [System.Net.ServicePointManager]::SecurityProtocol = ([System.Net.SecurityProtocolType]'Tls11,Tls12')
    $baseUrl = 'https://api.us.onelogin.com/api/1'
    $resourcePath = '/events'
    $httpVerb = "GET"
    $queryLimit = 50 # As of 30 August 2021, the maximum items returned by a call to this endpoint is 50. Chaninging this value higher results in HTTP 400.
    $headers = @{
        "Authorization" = "bearer $([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($AccessToken)))"
    }

    # Setup parameters for log splatting.
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') {
        If ($EventLogSource -and (-NOT $LogPath)) {
            $commandParams = @{
                Verbose        = $true
                EventLogSource = $EventLogSource
            }
        } ElseIf ($LogPath -and (-NOT $EventLogSource)) {
            $commandParams = @{
                Verbose = $true
                LogPath = $LogPath
            }
        } Else {
            $commandParams = @{
                Verbose = $true
            }
        }
    } Else {
        If ($EventLogSource -and (-NOT $LogPath)) {
            $commandParams = @{
                Verbose        = $False
                EventLogSource = $EventLogSource
            }
        } ElseIf ($LogPath -and (-NOT $EventLogSource)) {
            $commandParams = @{
                Verbose = $False
                LogPath = $LogPath
            }
        }
        Else {
            $commandParams = @{
                Verbose = $false
            }
        }
    }
    #endregion Setup

    #region Generate URL
    $message = ("{0}: Generating URL filters." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    If ($Username) {
        $message = ("{0}: Attempting to retrieve the ID of {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $Username)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $user = Get-OneLoginApiUser -AccessToken $AccessToken -Username $Username @commandParams

        If ($user.id) {
            $UserId = $user.id
        }
        Else {
            $message = ("{0}: User, {1} not found, skipping user filter." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
            If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Warning -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Warning -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Warning -Message $message }
        }
    }

    If ($ClientId) {
        $clientIdFilter = 'client_id={0}' -f $ClientId
    } Else {
        $clientIdFilter = 'client_id='
    }

    If ($DirectoryId) {
        $directoryFilter = 'directory_id={0}' -f $DirectoryId
    } Else {
        $directoryFilter = 'directory_id='
    }

    If ($EventId) {
        $eventIdFilter = 'id={0}' -f $EventId
    } Else {
        $eventIdFilter = 'id='
    }

    If ($Resolution) {
        $resolutionFilter = 'resolution={0}' -f $Resolution
    } Else {
        $resolutionFilter = 'resolution='
    }

    If ($UserId) {
        $userIdFilter = 'user_id={0}' -f $UserId
    } Else {
        $userIdFilter = 'user_id='
    }

    If ($Since) {
        $sinceFilter = 'since={0}' -f (([DateTime]$Since).ToUniversalTime()).ToString("yyyy-MM-dd`THH:mm:ssZ")
    }
    Else {
        $sinceFilter = 'since='
    }

    If ($Until) {
        $untilFilter = 'until={0}' -f (([DateTime]$Until).ToUniversalTime()).ToString("yyyy-MM-dd`THH:mm:ssZ")
    }
    Else {
        $untilFilter = 'until='
    }

    If ($EventTypeId) {
        $eventTypeIdFilter = 'event_type_id={0}' -f $EventTypeId
    }
    Else {
        $eventTypeIdFilter = 'event_type_id='
    }

    $queryParams = "?$eventTypeIdFilter&$sinceFilter&$untilFilter&$clientIdFilter&$directoryFilter&$eventIdFilter&$resolutionFilter&$userIdFilter&limit=$queryLimit"
    $url = "$baseUrl$resourcePath$queryParams"

    $message = ("{0}: The URL is: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $url)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }
    #endregion Generate URL

    #region get list of events - api v1
    Do {
        $message = ("{0}: Getting a page of events." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        Try {
            $response = Invoke-RestMethod -Method $httpVerb -UseBasicParsing -Uri $url -Headers $headers
        }
        Catch {
            $message = ("{0}: Unexpected error getting user. Error: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $_.Exception.Message)
            If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

            Exit 1
        }

        $message = ("{0}: Adding {1} events to the list." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $response.data.Count)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $events.AddRange([System.Collections.Generic.List[PSObject]]@($response.data))

        $message = ("{0}: There are {1} events in `$events." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $events.Count)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $url = $response.pagination.next_link
    }
    Until ($response.pagination.next_link -eq $null)
    #endregion get list of events - api v1

    $message = ("{0}: Returning {1} events." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $events.id.Count)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    $events
} #V1.0.0.0
Function Get-OneLoginApiUser {
    <#
        .DESCRIPTION
            Retrieve properties of one or more users (filtered based on ID, username, or samaccountname).
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 13 July 2021
                - Initial release
        .LINK
            https://github.com/wetling23/Public.OneLoginApi.PowerShellModule
        .PARAMETER AccessToken
            Represents a valid (not expired) OneLogin OATH token (https://developers.onelogin.com/api-docs/2/oauth20-tokens/generate-tokens-2).
        .PARAMETER Username
            Represents a user-specified list of OneLogin user names, for which to return the user objects. When excluded (and when ID/SamAccountName are not specified), all users will be returned.
        .PARAMETER Id
            Represents a user-specified list of OneLogin user IDs, for which to return the user objects. When excluded (and when Username/SamAccountName are not specified), all users will be returned.
        .PARAMETER SamAccountName
            Represents a user-specified list of OneLogin user names, for which to return the user objects. When excluded (and when Username/ID are not specified), all users will be returned.
        .PARAMETER QueryLimit
            Represents the maximum number of objects the API will return in a single call.
        .PARAMETER EventLogSource
            When included, (and when LogPath is null), represents the event log source for the Application log. If no event log source or path are provided, output is sent only to the host.
        .PARAMETER LogPath
            When included (when EventLogSource is null), represents the file, to which the cmdlet will output will be logged. If no path or event log source are provided, output is sent only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiUser -AccessToken <access token>
 
            Return all OneLogin users. Limited logging output will be written only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiUser -AccessToken <access token> -Username jsmith@domain.com
 
            Return the OneLogin users where the username is "jsmith@domain.com". Limited logging output will be written only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiUser -AccessToken <access token> -Id 34 -EventSource OneLoginScript
 
            Return the OneLogin users where the Id is "34". Limited logging output will be written to the event log and to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiUser -AccessToken <access token> -SamAccountName jsmith -Verbose -LogPath C:\Temp\log.txt
 
            Return the OneLogin users where the samaccountname is "jsmith". Verbose logging output will be written to C:\Temp\log.txt and to the host.
    #>

    [CmdletBinding(DefaultParameterSetName = 'allusers')]
    param (
        [Parameter(Mandatory)]
        [securestring]$AccessToken,

        [Parameter(ParameterSetName = 'username')]
        [string[]]$Username,

        [Parameter(ParameterSetName = 'id')]
        [int[]]$Id,

        [Parameter(ParameterSetName = 'samaccountname')]
        [string[]]$SamAccountName,

        [int]$QueryLimit = 1000,

        [string]$EventLogSource,

        [string]$LogPath
    )

    $message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $MyInvocation.MyCommand)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    # Initialize variables.
    $page = 1
    $stopLoop = $false
    $users = [System.Collections.Generic.List[PSObject]]::new()
    [System.Net.ServicePointManager]::SecurityProtocol = ([System.Net.SecurityProtocolType]'Tls11,Tls12')
    $baseUrl = 'https://api.us.onelogin.com/api/2'
    $resourcePath = '/users'
    $httpVerb = "GET"
    $headers = @{
        "Authorization" = "bearer $([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($AccessToken)))"
    }

    #region get a list of users - api v2 - ps v5.1
    Do {
        $queryParams = "?limit=$queryLimit&page=$page"

        $message = ("{0}: Getting page {1} of users." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $page)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        Try {
            $response = Invoke-RestMethod -Method $httpVerb -UseBasicParsing -Uri "$baseUrl$resourcePath$queryParams" -Headers $headers
        }
        Catch {
            $message = ("{0}: Unexpected error getting user. Error: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $_.Exception.Message)
            If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

            Exit 1
        }

        $message = ("{0}: Adding {1} users to the list." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $response.Count)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $users.AddRange([System.Collections.Generic.List[PSObject]]@($response))

        $message = ("{0}: There are {1} users in `$users." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $users.Count)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        If ($response.Count -lt $queryLimit) {
            $stopLoop = $true
        }

        $page++
    }
    Until ($stopLoop -eq $true)
    #endregion get a list of users - api v2 - ps v5.1

    Switch ($PsCmdlet.ParameterSetName) {
        "allusers" { Continue }
        { $_ -in ("username", "id", "samaccountname") } {
            $message = ("{0}: Filtering users." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
            If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }
        }
        "username" {
            $users = $users | Where-Object { $_.username -in $Username }
        }
        "id" {
            $users = $users | Where-Object { $_.id -in $Id }
        }
        "samaccountname" {
            $users = $users | Where-Object { $_.samaccountname -in $SamAccountName }
        }
    }

    $message = ("{0}: Returning {1} users." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $users.id.Count)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    $users

} #V1.0.0.0
Function Get-OneLoginAppList {
    <#
        .DESCRIPTION
            Returns apps configured in OneLogin.
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 1 October 2021
                - Initial release
        .LINK
            https://github.com/wetling23/Public.OneLoginApi.PowerShellModule
        .PARAMETER AccessToken
            Represents a valid (not expired), secure string OneLogin OATH token (https://developers.onelogin.com/api-docs/2/oauth20-tokens/generate-tokens-2).
        .PARAMETER Username
            Represents a OneLogin user name, for which to return matching events. When excluded, events for all users will be returned.
        .PARAMETER AuthMethod
            Represents a OneLogin authentication method value. Valid options are: Password, OpenId, Saml, Api, Google, Forms, WsFed, and OpenIdConnect. Note that this value is not the same as "auth_method_description".
        .PARAMETER Name
            Represents the name of the desired application.
        .PARAMETER EventLogSource
            When included, (and when LogPath is null), represents the event log source for the Application log. If no event log source or path are provided, output is sent only to the host.
        .PARAMETER LogPath
            When included (when EventLogSource is null), represents the file, to which the cmdlet will output will be logged. If no path or event log source are provided, output is sent only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token> -Name <app name> -Verbose
 
            In this example, the command will get all instances of apps called "<app name>". Verbose logging output will be written only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token> -Name <app name>* -LogPath C:\Temp\log.txt
 
            In this example, the command will get all instances of apps matching <app name>*, where "*" is a wildcard. Limited logging output will be written to C:\Temp\log.txt
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token> -AuthMethod Password
 
            In this example, the command will get all instances of apps with auth_method "Password". Limited logging output will be written only to the host.
        .EXAMPLE
            PS C:\> Get-OneLoginApiEvent -AccessToken <access token> -Name <app name> -AuthMethod Password
 
            In this example, the command will get all instances of apps with auth_method "Password" and called "<app name>". Limited logging output will be written only to the host.
    #>

    [CmdletBinding(DefaultParameterSetName = 'NoFilter')]
    param (
        [Parameter(Mandatory)]
        [securestring]$AccessToken,

        [ValidateSet('Password', 'OpenId', 'Saml', 'Api', 'Google', 'Forms', 'WsFed', 'OpenIdConnect')]
        [string]$AuthMethod,

        [string]$Name,

        [string]$EventLogSource,

        [string]$LogPath
    )

    $message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $MyInvocation.MyCommand)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    #region Setup
    # Initialize variables.
    $apps = [System.Collections.Generic.List[PSObject]]::new()
    [System.Net.ServicePointManager]::SecurityProtocol = ([System.Net.SecurityProtocolType]'Tls11,Tls12')
    $baseUrl = 'https://api.us.onelogin.com/api/2'
    $resourcePath = '/apps'
    $httpVerb = "GET"
    $page = 1
    $queryLimit = 1000 # As of 1 October 2021, the maximum items returned by a call to this endpoint is 1000. Chaninging this value higher results in HTTP 400.
    $queryFilter = $null
    $headers = @{
        "Authorization" = "bearer $([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($AccessToken)))"
    }

    # Setup parameters for log splatting.
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') {
        If ($EventLogSource -and (-NOT $LogPath)) {
            $commandParams = @{
                Verbose        = $true
                EventLogSource = $EventLogSource
            }
        } ElseIf ($LogPath -and (-NOT $EventLogSource)) {
            $commandParams = @{
                Verbose = $true
                LogPath = $LogPath
            }
        } Else {
            $commandParams = @{
                Verbose = $true
            }
        }
    } Else {
        If ($EventLogSource -and (-NOT $LogPath)) {
            $commandParams = @{
                Verbose        = $False
                EventLogSource = $EventLogSource
            }
        } ElseIf ($LogPath -and (-NOT $EventLogSource)) {
            $commandParams = @{
                Verbose = $False
                LogPath = $LogPath
            }
        }
        Else {
            $commandParams = @{
                Verbose = $false
            }
        }
    }
    #endregion Setup

    #region Generate URL
    $message = ("{0}: Generating URL filter." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    If ($AuthMethod) {
        Switch ($AuthMethod) {
            "Password" { $queryFilter = "auth_method=0" }
            "OpenId" { $queryFilter = "auth_method=1" }
            "Saml" { $queryFilter = "auth_method=2" }
            "Api" { $queryFilter = "auth_method=3" }
            "Google" { $queryFilter = "auth_method=4" }
            "Forms" { $queryFilter = "auth_method=6" }
            "Wsfed" { $queryFilter = "auth_method=7" }
            "OpenIdConnect" { $queryFilter = "auth_method=8" }
        }
    }

    If ($Name) {
        If ($queryFilter) {
            $queryFilter += "&name=$Name"
        }
        Else {
            $queryFilter = "name=$Name"
        }
    }

    $message = ("{0}: The URL is: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), "$baseUrl$resourcePath$queryParams")
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }
    #endregion Generate URL

    #region get all apps - api v2 - ps v7
    Do {
        $message = ("{0}: Getting page {1} of apps." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $page)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        If ($queryFilter) {
            $queryParams = "?$queryFilter&limit=$queryLimit&page=$page"
        }
        Else {
            $queryParams = "?limit=$queryLimit&page=$page"
        }

        Try {
            $response = Invoke-RestMethod -Method $httpVerb -UseBasicParsing -Uri "$baseUrl$resourcePath$queryParams" -Headers $headers -ResponseHeadersVariable responseHead -ErrorAction Stop
        }
        Catch {
            $message = ("{0}: Unexpected error getting apps. The specific error is: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $_.Exception.Message)
            If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message -BlockStdErr $BlockStdErr } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message -BlockStdErr $BlockStdErr } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message -BlockStdErr $BlockStdErr } }

            Return "Error"
        }

        $message = ("{0}: There are {1} pages of apps. Adding this batch to the list." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $page)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $apps.AddRange([System.Collections.Generic.List[PSObject]]@($response))

        $message = ("{0}: There are {1} apps in `$apps." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $apps.id.Count)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $page++
    }
    While ($apps.Count -ne ($responseHead.'Total-Count').Trim())
    #endregion get all apps - api v2 - ps v7

    $message = ("{0}: Returning {1} apps." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $apps.id.Count)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    $apps
} #V1.0.0.0

Function New-OneLoginApiBearerToken {
    <#
        .DESCRIPTION
            Retrieve OneLogin OAUTH bearer access token. See https://developers.onelogin.com/api-docs/1/getting-started/working-with-api-credentials for authentication details.
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 13 July 2021
                - Initial release
            V1.0.0.1 date: 22 July 2021
        .LINK
            https://github.com/wetling23/Public.OneLoginApi.PowerShellModule
        .PARAMETER ClientId
            Represents a API client ID, which exists in OneLogin.
        .PARAMETER ClientSecret
            Represents a API client secret, which exists in OneLogin.
        .PARAMETER EventLogSource
            When included, (and when LogPath is null), represents the event log source for the Application log. If no event log source or path are provided, output is sent only to the host.
        .PARAMETER LogPath
            When included (when EventLogSource is null), represents the file, to which the cmdlet will output will be logged. If no path or event log source are provided, output is sent only to the host.
        .EXAMPLE
            PS C:\> New-OneLoginApiBearerToken -ClientID <client ID> -ClientSecret (<client secret> | ConvertTo-SecureString -AsPlainText -Force)
 
            Returns a bearer token with expiration date/time in the UTC time zone. Limited logging output is sent to the host only.
        .EXAMPLE
            PS C:\> New-OneLoginApiBearerToken -ClientID <client ID> -ClientSecret (<client secret> | ConvertTo-SecureString -AsPlainText -Force) -LogPath C:\Temp\log.txt -Verbose
 
            Returns a bearer token with expiration date/time in the UTC time zone. Limited logging output is sent to the host only. Verbose logging output is sent to the host and C:\Temp\log.txt
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$ClientId,

        [Parameter(Mandatory)]
        [securestring]$ClientSecret,

        [string]$EventLogSource,

        [string]$LogPath
    )

    $message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $MyInvocation.MyCommand)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    # Initialize variables.
    [System.Net.ServicePointManager]::SecurityProtocol = ([System.Net.SecurityProtocolType]'Tls11,Tls12')
    $baseUrl = 'https://api.us.onelogin.com'
    $resourcePath = '/auth/oauth2/v2/token'
    $httpVerb = "POST"
    $encodedCred = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(('{0}:{1}' -f $ClientId, ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($ClientSecret))))))
    $headers = @{
        'Authorization' = "Basic $encodedCred"
        'Content-Type'  = 'application/json'
    }
    $data = @{
        "grant_type" = "client_credentials"
    } | ConvertTo-Json

    #region generate oauth token
    $message = ("{0}: Generating bearer token." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    Try {
        $response = Invoke-RestMethod -Method $httpVerb -UseBasicParsing -Uri "$baseUrl$resourcePath" -Headers $headers -Body $data
    }
    Catch {
        $message = ("{0}: Unexpected error retrieving bearer token. Error: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $_.Exception.Message)
        If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

        Return "Error"
    }

    If ($response.'access_token'.Length -gt 1) {
        $message = ("{0}: Bearer token retrieved, adding expiration date property." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $response | Add-Member -MemberType NoteProperty -Name expires_at -Value ((Get-Date -Date $response.created_at).AddSeconds($($response.'expires_in'))).ToUniversalTime().ToString("yyyy-MM-dd`THH:mm:ss") -Force

        $response
    }
    Else {
        $message = ("{0}: No bearer token retrieved." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
        If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

        Return "Error"
    }
    #endregion generate oauth token
} #V1.0.0.1
Function Out-OneLoginApiPsLogging {
    <#
        .DESCRIPTION
            Logging function, for host, event log, or a log file.
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 3 December 2019
                - Initial release.
            V1.0.0.1 date: 7 January 2020
            V1.0.0.2 date: 22 January 2020
            V1.0.0.3 date: 17 March 2020
            V1.0.0.4 date: 15 June 2020
            V1.0.0.5 date: 30 June 2020
            V1.0.0.6 date: 8 April 2021
            V1.0.0.7 date: 10 September 2021
            V1.0.0.8 date: 20 September 2021
        .LINK
            https://github.com/wetling23/logicmonitor-posh-module
        .PARAMETER EventLogSource
            Default parameter set. Represents the Windows Application log event source.
        .PARAMETER LogPath
            Path and file name of the target log file. If the file does not exist, the cmdlet will create it.
        .PARAMETER ScreenOnly
            When this switch parameter is included, the logging output is written only to the host.
        .PARAMETER Message
            Message to output.
        .PARAMETER MessageType
            Type of message to output. Valid values are "Info", "Warning", "Error", and "Verbose". When writing to a log file, all output is "info" but will be written to the host, with the appropriate message type.
        .PARAMETER BlockStdErr
            When set to $True, the cmdlet will block "Write-Error". Use this parameter when calling from wscript. This is required due to a bug in wscript (https://groups.google.com/forum/#!topic/microsoft.public.scripting.wsh/kIvQsqxSkSk).
        .EXAMPLE
            PS C:\> Out-PsLogging -Message "Test" -MessageType Info -LogPath C:\Temp\log.txt
 
            In this example, the message, "Test" will be written to the host and appended to C:\Temp\log.txt. If the path does not exist, or the user does not have write access, the message will only be written to the host.
        .EXAMPLE
            PS C:\> Out-PsLogging -Message "Test" -MessageType Warning -EventLogSource TestScript
 
            In this example, the message, "Test" will be written to the host and to the Windows Application log, as a warning and with the event log source/event ID "TestScript"/5417.
            If the event source does not exist and the session is elevated, the event source will be created.
            If the event source does not exist and the session is not elevated, the message will only be written to the host.
        .EXAMPLE
            PS C:\> Out-PsLogging -Message "Test" -MessageType Verbose -ScreenOnly
 
            In this example, the message, "Test" will be written to the host as a verbose message.
    #>

    [CmdletBinding(DefaultParameterSetName = 'SessionOnly')]
    param(
        [Parameter(Mandatory, ParameterSetName = 'EventLog')]
        [string]$EventLogSource,

        [ValidateScript( {
                If (-NOT ($_ | Split-Path -Parent | Test-Path) ) {
                    Throw "Path does not exist."
                }
                If (-NOT ($_ | Test-Path) ) {
                    "" | Add-Content -Path $_
                }
                If (-NOT ($_ | Test-Path -PathType Leaf) ) {
                    Throw "The LogPath argument must be a file."
                }
                Return $true
            })]
        [Parameter(Mandatory, ParameterSetName = 'File')]
        [System.IO.FileInfo]$LogPath,

        [switch]$ScreenOnly,

        [Parameter(Mandatory)]
        [string]$Message,

        [Parameter(Mandatory)]
        [ValidateSet('Info', 'Warning', 'Error', 'Verbose', 'First')]
        [string]$MessageType,

        [boolean]$BlockStdErr
    )

    # Initialize variables.
    $elevatedSession = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

    If ($PsCmdlet.ParameterSetName -eq "EventLog") {
        If ([System.Diagnostics.EventLog]::SourceExists("$EventLogSource")) {
            # The event source does not exists, nothing else to do.

            $logType = "EventLog"
        } ElseIf (-NOT ([System.Diagnostics.EventLog]::SourceExists("$EventLogSource")) -and $elevatedSession) {
            # The event source does not exist, but the session is elevated, so create it.
            Try {
                New-EventLog -LogName Application -Source $EventLogSource -ErrorAction Stop

                $logType = "EventLog"
            } Catch {
                Write-Error ("[ERROR] {0}: Unable to create the event source ({1}). No logging will be done." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $EventLogSource)

                $logType = "SessionOnly"
            }
        } ElseIf (-NOT $elevatedSession) {
            # The event source does not exist, and the session is not elevated.
            Write-Error ("[ERROR] {0}: The event source ({1}) does not exist and the command was not run in an elevated session, unable to create the event source. No logging will be done." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $EventLogSource)

            $logType = "SessionOnly"
        }
    } ElseIf ($PsCmdlet.ParameterSetName -eq "File") {
        # Check if we have rights to the path in $LogPath.
        Try {
            [System.Io.File]::OpenWrite($LogPath).Close()
        } Catch {
            Write-Error ("[ERROR] {0}: Unable to write to the log file path ({1}). No logging will be done." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $LogPath)

            $logType = "SessionOnly"
        }

        $logType = "LogFile"
    } Else {
        $logType = "SessionOnly"
    }

    Switch ($logType) {
        "SessionOnly" {
            Switch ($MessageType) {
                "Info" { Write-Host "[INFO] $Message" }
                "Warning" { Write-Warning "[WARNING] $Message" }
                "Error" { If ($BlockStdErr) { Write-Host "[ERROR] $Message" -ForegroundColor Red } Else { Write-Error "[ERROR] $Message" } }
                "Verbose" { Write-Verbose "[VERBOSE] $Message" -Verbose }
                "First" { Write-Verbose "[INFO] $Message" -Verbose }
            }
        }
        "EventLog" {
            Switch ($MessageType) {
                "Info" { Write-EventLog -LogName Application -Source $EventLogSource -EntryType Information -Message "[INFO] $Message" -EventId 5417; Write-Host "[INFO] $Message" }
                "Warning" { Write-EventLog -LogName Application -Source $EventLogSource -EntryType Warning -Message "[WARNING] $Message" -EventId 5417; Write-Warning "[WARNING] $Message" }
                "Error" { Write-EventLog -LogName Application -Source $EventLogSource -EntryType Error -Message "[ERROR] $Message" -EventId 5417; If ($BlockStdErr) { Write-Host "[ERROR] $Message" -ForegroundColor Red } Else { Write-Error "[ERROR] $Message" } }
                "Verbose" { Write-EventLog -LogName Application -Source $EventLogSource -EntryType Information -Message "[VERBOSE] $Message" -EventId 5417; Write-Verbose "[VERBOSE] $Message" -Verbose }
                "First" { Write-EventLog -LogName Application -Source $EventLogSource -EntryType Information -Message "[INFO] $Message" -EventId 5417; Write-Verbose "[INFO] $Message" -Verbose }
            }
            If ($BlockStdErr) {

            }
        }
        "LogFile" {
            Switch ($MessageType) {
                "Info" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]"[INFO] $Message", [Text.Encoding]::UTF8); Write-Host "[INFO] $Message" }
                "Warning" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]"[WARNING] $Message", [Text.Encoding]::UTF8); Write-Warning "[WARNING] $Message" }
                "Error" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]"[ERROR] $Message", [Text.Encoding]::UTF8); If ($BlockStdErr) { Write-Host "[ERROR] $Message" -ForegroundColor Red } Else { Write-Error "[ERROR] $Message" } }
                "Verbose" { [System.IO.File]::AppendAllLines([string]$LogPath, [string[]]"[VERBOSE] $Message", [Text.Encoding]::UTF8); Write-Verbose "[VERBOSE] $Message" -Verbose }
                "First" { [System.IO.File]::WriteAllLines($LogPath, "[INFO] $Message", [Text.Encoding]::UTF8); Write-Verbose "[INFO] $Message" -Verbose }
            }
        }
    }
} #1.0.0.8

Function Update-OneLoginApiUserProperty {
    <#
        .DESCRIPTION
            Accepts a hashtable of user properties and user identifier (ID, username, or samaccountname) and updates the property(ies).
        .NOTES
            Author: Mike Hashemi
            V1.0.0.0 date: 13 July 2021
                - Initial release
                - https://developers.onelogin.com/api-docs/1/users/update-user
        .LINK
            https://github.com/wetling23/Public.OneLoginApi.PowerShellModule
        .PARAMETER AccessToken
            Represents a valid (not expired) OneLogin OATH token (https://developers.onelogin.com/api-docs/2/oauth20-tokens/generate-tokens-2).
        .PARAMETER Username
            Represents a OneLogin user name, for a user to update. If provided, the command will query OneLogin to retrieve the ID.
        .PARAMETER Id
            Represents a OneLogin ID, for a user to update.
        .PARAMETER SamAccountName
            Represents a OneLogin samaccountname, for a user to update. If provided, the command will query OneLogin to retrieve the ID.
        .PARAMETER QueryLimit
            Represents the maximum number of objects the API will return in a single call.
        .PARAMETER EventLogSource
            When included, (and when LogPath is null), represents the event log source for the Application log. If no event log source or path are provided, output is sent only to the host.
        .PARAMETER LogPath
            When included (when EventLogSource is null), represents the file, to which the cmdlet will output will be logged. If no path or event log source are provided, output is sent only to the host.
        .EXAMPLE
            PS C:\> Update-OneLoginApiUser -AccessToken <access token> -Username jsmith@domain.com -Properties @{ "group_id" = 123 }
 
            Add the user "jsmith@synoptek.com" to the OneLogin group with ID 123. Note that the group_id property must be an integer (not enclosed in quotes). Limited logging output is written to the host only.
        .EXAMPLE
            PS C:\> Update-OneLoginApiUser -AccessToken <access token> -SamAccountName jsmith -Properties @{ "group_id" = '' }
 
            Remove the user "jsmith@synoptek.com" from the OneLogin group. Limited logging output is written to the host only.
        .EXAMPLE
            PS C:\> Update-OneLoginApiUser -AccessToken <access token> -Id 123456 -Properties @{ "notes" = "mike is great"; "group_id" = 123 } -Verbose -LogPath C:\Temp\log.txt
 
            Add the user "jsmith@synoptek.com" to the OneLogin group with ID 123 and add a note with the value, "mike is great". Note that the group_id property MUST be an integer (not enclosed in quotes) and the notes properties MUST be a string (enclosed in double quotes). Verbose logging will be written to C:\Temp\log.txt and written to the host.
    #>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [securestring]$AccessToken,

        [Parameter(Mandatory, ParameterSetName = 'username')]
        [string]$Username,

        [Parameter(Mandatory, ParameterSetName = 'id')]
        [int]$Id,

        [Parameter(Mandatory, ParameterSetName = 'samaccountname')]
        [string]$SamAccountName,

        [hashtable]$Properties,

        [string]$EventLogSource,

        [string]$LogPath
    )

    $message = ("{0}: Beginning {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $MyInvocation.MyCommand)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    #region Setup
    # Initialize variables.
    [System.Net.ServicePointManager]::SecurityProtocol = ([System.Net.SecurityProtocolType]'Tls11,Tls12')
    $errorState = 0
    $baseUrl = 'https://api.us.onelogin.com/api/1'
    $httpVerb = "PUT"
    $headers = @{
        "Authorization" = "bearer $([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($AccessToken)))"
        "Content-Type"  = "application/json"
    }
    $body = $Properties | ConvertTo-Json -Depth 10

    # Setup parameters for splatting.
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') {
        If ($EventLogSource -and (-NOT $LogPath)) {
            $commandParams = @{
                Verbose        = $true
                EventLogSource = $EventLogSource
            }
        } ElseIf ($LogPath -and (-NOT $EventLogSource)) {
            $commandParams = @{
                Verbose = $true
                LogPath = $LogPath
            }
        } Else {
            $commandParams = @{
                Verbose = $true
            }
        }
    } Else {
        If ($EventLogSource -and (-NOT $LogPath)) {
            $commandParams = @{
                Verbose        = $False
                EventLogSource = $EventLogSource
            }
        } ElseIf ($LogPath -and (-NOT $EventLogSource)) {
            $commandParams = @{
                Verbose = $False
                LogPath = $LogPath
            }
        } Else {
            $commandParams = @{
                Verbose = $false
            }
        }
    }

    Switch ($PsCmdlet.ParameterSetName) {
        { $_ -in ("username", "samaccountname") } {
            $message = ("{0}: Attempting to retrieve user ID." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
            If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }
        }
        "username" {
            $id = (Get-OneLoginApiUser -AccessToken $AccessToken -Username $Username @commandParams).id
        }
        "samaccountname" {
            $id = (Get-OneLoginApiUser -AccessToken $AccessToken -SamAccountName $SamAccountName @commandParams).id
        }
    }

    If ($id -as [int]) {
        $message = ("{0}: The user's ID is: {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $id)
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

        $resourcePath = "/users/{0}" -f $id
    }
    Else {
        $message = ("{0}: Unable to locate the user. {1} will exit." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $MyInvocation.MyCommand)
        If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

        Return "Error"
    }
    #endregion Setup

    $message = ("{0}: Attempting to update the user: {1}." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $Id)
    If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }

    Try {
        $response = Invoke-RestMethod -Method $httpVerb -UseBasicParsing -Uri "$baseUrl$resourcePath" -Headers $headers -Body $body -ErrorAction Stop
    }
    Catch {
        $message = ("{0}: Unexpected error updating user. If available, the body is:`r`n{1}`r`n`r`nError: {2}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), ($body | Out-String), $_.Exception.Message)
        If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

        Return "Error"
    }

    If ($response.status.error -eq $false) {
        $message = ("{0}: Successfully updated the user." -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"))
        If ($PSBoundParameters['Verbose'] -or $VerbosePreference -eq 'Continue') { If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Verbose -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Verbose -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Verbose -Message $message } }
    }
    Else {
        $message = ("{0}: Failed to update user: {1}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $_.Exception.Message)
        If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

        $message = ("{0}: If available, the following was returned:`r`n`tError: {1}`r`n`tCode: {2}`r`n`tType: {3}`r`n`tMessages: {4}" -f ([datetime]::Now).ToString("yyyy-MM-dd`THH:mm:ss"), $response.status.error, $response.status.code, $response.status.type, $response.status.message)
        If ($EventLogSource -and (-NOT $LogPath)) { Out-PsLogging -EventLogSource $EventLogSource -MessageType Error -Message $message } ElseIf ($LogPath -and (-NOT $EventLogSource)) { Out-PsLogging -LogPath $LogPath -MessageType Error -Message $message } Else { Out-PsLogging -ScreenOnly -MessageType Error -Message $message }

        $errorState = 1
    }

    If ($errorState -eq 1) {
        Return "Error"
    }
    Else {
        Return "Success"
    }
} #V1.0.0.0
Export-ModuleMember -Alias * -Function *