lib/Tasks.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
function Get-TMTask {
    <#
    .SYNOPSIS
    Gets one or more Tasks from TransitionManager using optional filters

    .DESCRIPTION
    This function gets one or more Tasks from TransitionManager by Id, Number,
    Task Spec Id, Status, Asset Name, Asset Type, Action Name, or Category.

    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection

    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used

    .PARAMETER TMEvent
    The TMEvent object representing the Event to use as a filter for the Tasks retrieved

    .PARAMETER Id
    One or more Task Ids to filter by

    .PARAMETER TaskNumber
    One or more Task numbers to filter by

    .PARAMETER TaskSpecId
    One or more Task spec Ids to filter by

    .PARAMETER Status
    One or more Statuses to filter by
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated

    .PARAMETER AssetName
    One or more Asset names to filter by

    .PARAMETER AssetType
    One or more Asset types to filter by

    .PARAMETER ActionName
    One or more Action names to filter by

    .PARAMETER Category
    One or more Task categories to filter by

    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints

    .EXAMPLE
    $TMEvent = Get-TMEvent -TMSession $ProfileName -Name $EventName -ProjectId $ProjectId
    Get-TMTask -TMSession $ProfileName -Status 'Completed', 'Ready' -Event $TMEvent

    .OUTPUTS
    One or more TMTask objects representing the results of the filtered search
    #>


    [OutputType([TMTask[]])]
    [CmdletBinding(DefaultParameterSetName = 'All')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $false, Position = 1)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId = $TMSessions[$TMSession].UserContext.Project.Id,

        [Parameter(Mandatory = $false)]
        [Alias('Event')]
        [TMEvent]$TMEvent,

        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'ById')]
        [Int[]]$Id,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByTaskNumber')]
        [Alias('Number')]
        [Int[]]$TaskNumber,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByTaskSpec')]
        [Alias('TaskSpec')]
        [Int[]]$TaskSpecId,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByStatus')]
        [ArgumentCompleter({ [TMTask]::ValidStatuses })]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [String[]]$Status,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByAssetName')]
        [String[]]$AssetName,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByAssetType')]
        [String[]]$AssetType,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByActionName')]
        [String[]]$ActionName,

        [Parameter(Mandatory = $true, ParameterSetName = 'ByCategory')]
        [String[]]$Category,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )


    begin {
        function Get-FilteredTasksAPI($SessionConfig, $JsonBody) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()
            $RestSplat = @{
                Uri        = "https://$($SessionConfig.TMServer)/tdstm/api/task?rows=1000&page=1"
                Method     = 'GET'
                WebSession = $SessionConfig.TMRestSession
                Body       = $JsonBody
            }
            $Response = Invoke-RestMethod @RestSplat

            ## Assign the Rows variable based on what TM provides back
            if ($Response.PSObject.Properties.Name -contains 'rows') {
                $Rows = $Response.rows
            }
            elseif ($Response.PSObject.Properties.Name -contains 'records') {
                $Rows = $Response.records
            }
            elseif ($Response.PSObject.Properties.Name -contains 'tasks') {
                $Rows = $Response.tasks
            }
            foreach ($Row in $Rows) {
                try {
                    $TaskList.Add([TMTask]::new($Row))
                }
                catch {
                    Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                }
            }

            if ($Response.total -gt 1) {
                for ($i = 2; $i -le $Response.total; $i++) {
                    $RestSplat.Uri = "https://$($TMSessionConfig.TMServer)/tdstm/api/task?rows=1000&page=$i"
                    $Response = Invoke-RestMethod @RestSplat

                    ## Assign the Rows variable based on what TM provides back
                    if ($Response.PSObject.Properties.Name -contains 'rows') {
                        $Rows = $Response.rows
                    }
                    elseif ($Response.PSObject.Properties.Name -contains 'records') {
                        $Rows = $Response.records
                    }
                    elseif ($Response.PSObject.Properties.Name -contains 'tasks') {
                        $Rows = $Response.tasks
                    }

                    foreach ($Row in $Rows) {
                        try {
                            $TaskList.Add([TMTask]::new($Row))
                        }
                        catch {
                            Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                        }
                    }
                }
            }

            # ## TM v6.0.2.1 is currently not honoring Event filteing by name on the API. Remove any that shouldn't be there
            if ($TMEvent -and $TMSessionConfig.TMVersion -ge '6.0.2.1') {

                $UnfilteredTaskList = $TaskList
                $TaskList = [System.Collections.Generic.List[TMTask]]::new()
                foreach($Task in $UnfilteredTaskList){
                    if($Task.Event.Name -eq $TMEvent.name){
                        $TaskList.Add($Task)
                    }
                }
            }
            , $TaskList
        }


        function Get-FilteredTasksWS($SessionConfig, [Hashtable]$Filter) {
            $TaskList = [System.Collections.Generic.List[TMTask]]::new()

            $FilterStrings = @()
            foreach ($Key in $Filter.Keys) {
                $FilterStrings += "$($Key)=$([System.Web.HttpUtility]::UrlEncode($Filter.$Key))"
            }
            $WebRequestSplat = @{
                Uri        = "https://$($SessionConfig.TMServer)/tdstm/ws/task?" + ($FilterStrings -join '&')
                Method     = "GET"
                WebSession = $SessionConfig.TMWebSession
            }
            $Response = Invoke-WebRequest @WebRequestSplat
            if ($Response.StatusCode -in 200, 204) {
                $ResponseContent = $Response.Content | ConvertFrom-Json
                foreach ($Row in $ResponseContent.data) {
                    try {
                        $TaskList.Add([TMTask]::new($Row))
                    }
                    catch {
                        Write-Warning "Could not retrieve task # $($Row.TaskNumber): $($_.Exception.Message)"
                    }
                }
            }

            , $TaskList
        }

        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id

        # $Tasks = [System.Collections.ArrayList]::new()
        $Tasks = [System.Collections.Generic.List[TMTask]]::new()

        # Determine which endpoint to hit based on the TM version and REST session and set up the base filters
        # REST = REST API
        # WS50 = Web Services using ATE
        # WS47 = Web Services without ATE
        if ($TMSessionConfig.TMRestSession -and $Api) {
            $Endpoint = 'REST'
            $Filters = @{
                project = $ProjectId
            }

            if ($TMEvent) {
                $Filters.event = @{name = $TMEvent.Name }
            }

            ## Wrap the request with the right syntax for Newer API version requirements
            if ($TMSessionConfig.TMVersion -ge '6.0.1.2') {
                $Filters = @{filter = $Filters; project = $ProjectId  }
            }
        }
        else {
            $Endpoint = $TMSessionConfig.TMVersion -like '4.*' ? 'WS47' : 'WS50'
            $Filters = @{
                projectId = $ProjectId
            }

            if ($TMEvent) {
                $Filters.moveEvent = $TMEvent.Id
            }
        }
    }

    process {
        switch ($PSCmdlet.ParameterSetName) {
            'ById' {
                switch ($Endpoint) {
                    'REST' {
                        $Id | ForEach-Object {
                            $RestSplat = @{
                                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($_)?project=$($ProjectId)"
                                Method     = 'GET'
                                WebSession = $TMSessionConfig.TMRestSession
                            }
                            $Response = Invoke-RestMethod @RestSplat
                            $Tasks.Add([TMTask]::new($Response))
                        }
                    }
                    {  $_ -in 'WS50',  'WS47'  } {
                        $Id | ForEach-Object {
                            $WebRequestSplat = @{
                                Uri               = "https://$($TMSessionConfig.TMServer)/tdstm/assetEntity/showComment?id=$($_)"
                                Method         = 'GET'
                                WebSession = $TMSessionConfig.TMWebSession
                            }
                            $Response = Invoke-WebRequest @WebRequestSplat
                            if ($Response.StatusCode -in 200, 204) {
                                $ResponseContent = $Response.Content | ConvertFrom-Json
                                $Tasks.Add([TMTask]::new($ResponseContent.assetComment))
                            }
                        }
                    }
                }
            }

            'ByTaskNumber' {
                switch ($Endpoint) {
                    'REST' {
                        $TaskNumber | ForEach-Object {
                            $Filters.taskNumber = $_
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.taskNumber = $TaskNumber -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $TaskNumber | ForEach-Object {
                            $Filters.taskNumber = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByTaskSpec' {
                switch ($Endpoint) {
                    {  $_ -in 'REST', 'WS50'  } {

                        # Because the WS endpoint is being hit, make sure there is a projectId filter instead of project
                        $Filters.Remove('project')
                        $Filters.projectId = $ProjectId
                        $Filters.taskSpec = $TaskSpecId -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $TaskSpecId | ForEach-Object {
                            $Filters.taskSpec = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByStatus' {
                switch ($Endpoint) {
                    'REST' {
                        $Status | ForEach-Object {
                            $Filters.status = $_
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.status = $Status -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $Status | ForEach-Object {
                            $Filters.status = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByAssetName' {
                switch ($Endpoint) {
                    'REST' {
                        $AssetName | ForEach-Object {
                            $Filters.asset = @{ name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.assetName = $AssetName -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $AssetName | ForEach-Object {
                            $Filters.assetName = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByAssetType' {
                switch ($Endpoint) {
                    'REST' {
                        $AssetType | ForEach-Object {
                            $Filters.asset = @{name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.assetName = $AssetType -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $AssetType | ForEach-Object {
                            $Filters.assetName = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByActionName' {
                switch ($Endpoint) {
                    'REST' {
                        $ActionName | ForEach-Object {
                            $Filters.action = @{name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.apiAction = $ActionName -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $ActionName | ForEach-Object {
                            $Filters.apiAction = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            'ByCategory' {
                switch ($Endpoint) {
                    'REST' {
                        $Category | ForEach-Object {
                            $Filters.category = @{name = $_ }
                            $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                        }
                    }
                    'WS50' {
                        $Filters.category = $Category -join '|'
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                    'WS47' {
                        $ActionName | ForEach-Object {
                            $Filters.category = $_
                            $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                        }
                    }
                }
            }

            default {
                switch ($Endpoint) {
                    'REST' {
                        $Tasks.AddRange((Get-FilteredTasksAPI -SessionConfig $TMSessionConfig -JsonBody ($Filters | ConvertTo-Json)))
                    }
                    { $_ -in 'WS50', 'WS47' } {
                        $Tasks.AddRange((Get-FilteredTasksWS -SessionConfig $TMSessionConfig -Filter $Filters))
                    }
                }

            }
        }

        $Tasks
    }
}


function Update-TMTask {
    <#
    .SYNOPSIS
    Updates a Task in TransitionManager

    .DESCRIPTION
    This function will update a Task in TransitionManager using a TMTask object that represents
    the desired changes

    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection

    .PARAMETER Task
    The TMTask object representing the required changes

    .PARAMETER Note
    A note to be added to the updated Task

    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints

    .PARAMETER Passthru
    Switch indicating that the Task should be returned after being updated

    .EXAMPLE
    # Get an existing Task from TransitionManager
    $Task = Get-TMTask -TMSession TMAD50 -TaskNumber 1

    # Change the Action associated with the Task
    $Task.Action.Id = 175

    # Remove the user assignment
    $Task.AssignedTo.Id = 0

    # Set the Task's status to Pending
    $Task.Status = 'Pending'

    # Change the Asset associated with the Task
    $Task.Asset.Id = 232053

    # Use the updated TMTask object to commit the changes to TransitionManager
    Update-TMTask -TMSession TMAD50 -Task $Task

    .OUTPUTS
    If the Passthru switch was provided, then a TMTask object is returned. Otherwise, none

    .NOTES
    Below are the available Task properties that can be updated along with the associated
    TMTask property to be changed:

    Action: TMTask.Action.Id
    Asset: TMTask.Asset.Id
    Event: TMTask.Event.Id
    AssignedTo: TMTask.AssignedTo.Id
    Category: TMTask.Category
    Title: TMTask.Title
    HardAssigned: TMTask.HardAssigned
    InstructionsLink: TMTask.InstructionsLink
    PercentageComplete: TMTask.PercentageComplete
    Priority: TMTask.Priority
    Team: TMTask.Team
    Status: TMTask.Status
    SendNotification: TMTask.SendNotification
    Project: TMTask.Project.Id
    predecessors: TMTask.Predecessors
    successors: TMTask.Successors
    #>


    [CmdletBinding()]
    [Alias('Set-TMTask')]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [Alias('InputObject')]
        [TMTask]$Task,

        [Parameter(Mandatory = $false)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru
    )


    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri                = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Task.Id)"
                Method             = 'PUT'
                WebSession         = $TMSessionConfig.TMRestSession
                SkipHttpErrorCheck = $true
                StatusCodeVariable = 'StatusCode'
                Body               = ($Task.GetApiUpdateObject($Note) | ConvertTo-Json -Depth 3 -Compress)
            }

            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                if ($StatusCode -in 200, 204) {
                    if ($Passthru) {
                        [TMTask]::new($Response)
                    }
                }
                elseif (-not [String]::IsNullOrWhiteSpace($Response)) {
                    throw $Response
                }
                else {
                    throw "The response status code $StatusCode does not indicate success."
                }
            }
            catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri         = "https://$($TMSessionConfig.TMServer)/tdstm/ws/task/saveTask"
                Method         = 'POST'
                WebSession     = $TMSessionConfig.TMWebSession
                Body         = ($Task.GetWSUpdateObject() | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -in 200, 204) {
                    if (-not [String]::IsNullOrWhiteSpace($Note)) {
                        Add-TMTaskNote -TMSession $TMSession -Id $Task.Id -Note $Note
                    }
                    if ($Passthru) {
                        try {
                            [TMTask]::new(($Response.Content | ConvertFrom-Json).data.assetComment)
                        }
                        catch {
                            Write-Warning "Update was successful, but the updated Task could not be returned. Use Get-TMTask to retrieve the updated Task object."
                        }
                    }
                }
                else {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
    }
}


function New-TMTask {
    <#
    .SYNOPSIS
    Creates a new Task in TransitionManager

    .DESCRIPTION
    This function will create a new Task in TransitionManager either by using the specified
    properties or by using a TMTask object

    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection

    .PARAMETER Task
    A TMTask object representing the new Task to be created

    .PARAMETER Title
    The title of the new Task

    .PARAMETER EventId
    The Id of the Event in which to place the new Task

    .PARAMETER ProjectId
    The Id of the TransitionManager project in which to place the new Task. If this is not provided,
    the project from the TMSession will be used

    .PARAMETER Status
    The status of the new Task
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated

    .PARAMETER Team
    The team to be assigned to the new Task

    .PARAMETER Priority
    The priority of the new Task

    .PARAMETER InstructionsLink
    The instructions link to place on the new Task

    .PARAMETER Duration
    The duration of the new task

    .PARAMETER SendNotification
    Indicates if the new Task should send notifications

    .PARAMETER Category
    The category of the new Task

    .PARAMETER AssignedToId
    The Id of the person that should be assigned to the new Task

    .PARAMETER AssetId
    The Id of the Asset to be associated with the new Task

    .PARAMETER ActionId
    The Id of the Action to be associated with the new Task

    .PARAMETER Predecessor
    One or more Task Ids that will be linked as a predecessor on the new Task

    .PARAMETER Successor
    One or more Task Ids that will be linked as a succecessor on the new Task

    .PARAMETER Note
    A note to be added to the new Task

    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints

    .PARAMETER Passthru
    Switch indicating that the new Task should be returned after creation

    .EXAMPLE
    $NewTaskSplat = @{
        TMSession = "TMAD60"
        Title = "Test Task - w/ Dependencies"
        EventId = 460
        ProjectId = 6269
        Status = "Ready"
        Team = 'SYS_ADMIN'
        AssignedToId = 6246
        AssetId = 232053
        Successor = 369638, 411521
        Predecessor = 411702
        Note = "This was created via PowerShell"
        Passthru = $true
        ActionId = 178
    }
    New-TMTask @NewTaskSplat

    .EXAMPLE
    This example gets an existing task and then changes the associated Action
    and Title as well as removes all predecessors

    $Task = Get-TMTask -TMSession TMAD50 -Id $NewTask.id
    $Task.Action.Id = 177
    $Task.Title = "Copy of $($NewTask.TaskNumber)"
    $Task.Predecessors = @()
    New-TMTask -TMSession TMAD50 -Task $Task -Note "This task was created as a modified copy of $($Task.Id)"


    .OUTPUTS
    If the Passthru switch was provided, then a TMTask object is returned. Otherwise, none
    #>


    [CmdletBinding(DefaultParameterSetName = 'ByProperty')]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true,
            ValueFromPipeline = $true,
            ParameterSetName = 'ByObject')]
        [Alias('InputObject')]
        [TMTask]$Task,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ByProperty')]
        [String]$Title,

        [Parameter(Mandatory = $true,
            ParameterSetName = 'ByProperty')]
        [Int]$EventId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ArgumentCompleter( { [TMTask]::ValidStatuses } )]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [String]$Status = 'Pending',

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [String]$Team,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ValidateRange(1, 5)]
        [Int]$Priority = 3,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [String]$InstructionsLink,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$Duration = 0,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Bool]$SendNotification = $false,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [ArgumentCompleter( { [TMTask]::ValidCategories } )]
        [ValidateScript( { $_ -in [TMTask]::ValidCategories } )]
        [String]$Category = 'general',

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$AssignedToId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$AssetId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int]$ActionId,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int[]]$Predecessor,

        [Parameter(Mandatory = $false,
            ParameterSetName = 'ByProperty')]
        [Int[]]$Successor,

        [Parameter(Mandatory = $false)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true,

        [Parameter(Mandatory = $false)]
        [Switch]$Passthru
    )


    begin {

        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {
        if ($PSCmdlet.ParameterSetName -eq 'ByObject') {
            $Title = $Task.Title
            $EventId = $Task.Event.Id
            $ProjectId = $Task.Project.Id
            $Status = $Task.Status
            $Team = $Task.Team
            $Priority = $Task.Priority
            $InstructionsLink = $Task.InstructionsLink
            $Category = $Task.Category
            $AssignedToId = $Task.AssignedTo.Id
            $AssetId = $Task.Asset.Id
            $ActionId = $Task.Action.Id
            $Predecessor = $Task.Predecessors.TaskId
            $Successor = $Task.Successors.TaskId
            $SendNotification = $Task.SendNotification
            $Duration = $Task.Duration
        }

        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"

            Write-Verbose "Forming web request body"
            $Body = @{
                title            = $Title
                event            = @{ id = $EventId }
                project          = $ProjectId
                status           = $Status
                priority         = $Priority
                category         = $Category
                action           = @{ id = $ActionId }
                role             = $Team
                duration         = $Duration
                instructionsLink = $InstructionsLink
                assignedTo       = $AssignedToId
                asset            = @{ id = $AssetId }
                note             = $Note
                sendNotification = $SendNotification ? 1 : 0
                predecessors     = @()
                successors       = @()
            }
            if ($null -ne $Predecessor) {
                $Predecessor | ForEach-Object {
                    $Body.predecessors += @{
                        id     = -1
                        taskId = $_
                    }
                }
            }
            if ($null -ne $Successor) {
                $Successor | ForEach-Object {
                    $Body.successors += @{
                        id     = -1
                        taskId = $_
                    }
                }
            }
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMRestSession
                Body       = ($Body | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                if ($Passthru) {
                    [TMTask]::new($Response)
                }
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            $Body = @{
                comment          = $Title
                status           = $Status
                assignedTo       = $AssignedToId
                apiAction        = $ActionId
                apiActionId      = $ActionId
                category         = $Category
                assetEntity      = $AssetId
                moveEvent        = $EventId
                priority         = $Priority
                role             = $Team
                sendNotification = $SendNotification ? 1 : 0
                instructionsLink = $InstructionsLink
                duration         = $Duration
                durationScale    = "M"
                durationLocked   = 0
                manageDependency = 0
                taskDependency   = @()
                taskSuccessor    = @()
            }

            if ($null -ne $Predecessor) {
                $Predecessor | ForEach-Object {
                    $Body.taskDependency += "-1_$($_)"
                }
                $Body.manageDependency = 1
            }
            if ($null -ne $Successor) {
                $Successor | ForEach-Object {
                    $Body.taskSuccessor += "-1_$($_)"
                }
                $Body.manageDependency = 1
            }

            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/ws/task/saveTask"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMWebSession
                Body       = ($Body | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -in 200, 204) {
                    if ($Passthru) {
                        try {
                            [TMTask]::new(($Response.Content | ConvertFrom-Json).data.assetComment)
                        }
                        catch {
                            Write-Warning "Update was successful, but the updated Task could not be returned. Use Get-TMTask to retrieve the updated Task object."
                        }
                    }
                }
                else {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
    }
}


function Remove-TMTask {
    <#
    .SYNOPSIS
    Deletes a Task from TransitionManager

    .DESCRIPTION
    This function will delete one or more of the specified Tasks from TransitionManager

    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection

    .PARAMETER Id
    The Id of the task to be deleted

    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints

    .EXAMPLE
    Remove-TMTask -Id 587434

    .EXAMPLE
    Get-TMTask -Id 129874, 458696 | Remove-TMTask

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true, Position = 1, ValueFromPipeline = $true)]
        [Int[]]$Id,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            foreach ($TaskId in $Id) {
                Write-Verbose "Forming web request parameters"
                $RestSplat = @{
                    Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Id)"
                    Method     = 'DELETE'
                    WebSession = $TMSessionConfig.TMRestSession
                }
                Write-Debug "Web Request Parameters:"
                Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
                Write-Verbose "Invoking REST method"
                try {
                    $Response = Invoke-RestMethod @RestSplat
                    Write-Debug "Response:"
                    Write-Debug ($Response | ConvertTo-Json -Depth 10)
                }
                catch {
                    throw "Error while deleting task: $($_.Exception.Message)"
                }
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/ws/asset/comment/$($Id)"
                Method     = 'DELETE'
                WebSession = $TMSessionConfig.TMWebSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while updating task: $($_.Exception.Message)"
            }
        }
    }
}


function Set-TMTaskStatus {
    <#
    .SYNOPSIS
    Sets the status of a TransitionManager Task

    .DESCRIPTION
    This function will set/update the status of the specified Task in TransitionManager

    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection

    .PARAMETER Id
    The Id of Task on which the status will be set

    .PARAMETER Status
    The new status to set on the task
    Valid values are: Hold, Planned, Ready, Pending, Started, Completed, Terminated

    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used

    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints

    .EXAMPLE
    Set-TMTaskStatus -TMSession TMAD50 -Id 411521 -Status Ready

    .EXAMPLE
    Get-TMTask -TaskNumber 189, 2569 | Set-TMTaskStatus -Status Ready

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('TaskId')]
        [Int]$Id,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [ArgumentCompleter({ [TMTask]::ValidStatuses })]
        [ValidateScript( { $_ -in [TMTask]::ValidStatuses } )]
        [Alias('State')]
        [String]$Status,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Id)/updateStatus?status=$Status&project=$ProjectId"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMRestSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                Write-Debug "Response:"
                Write-Debug ($Response | ConvertTo-Json -Depth 10)
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/assetEntity/updateComment"
                Method     = 'POST'
                WebSession = $TMSessionConfig.TMWebSession
                Body       = (@{
                        id     = $Id
                        status = $Status
                    } | ConvertTo-Json -Compress)
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while setting task status to $($Status): $($_.Exception.Message)"
            }
        }
    }
}


function Add-TMTaskNote {
    <#
    .SYNOPSIS
    Adds a note to the specified Task

    .DESCRIPTION
    This function will add the specified note to a TransitionManager Task

    .PARAMETER TMSession
    The name of the TM Session containing a TransitionManager connection

    .PARAMETER Id
    The Id of the Task to which the note should be added

    .PARAMETER Note
    The note to be added

    .PARAMETER ProjectId
    The Id of the TransitionManager project. If this is not provided,
    the project from the TMSession will be used

    .PARAMETER Api
    Boolean indicating that REST API endpoints should be used in favor of web service endpoints

    .EXAMPLE
    Add-TMTaskNote -TMSession TMAD50 -Id 12356 -Note "This task was updated via PowerShell"

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $false, Position = 0)]
        [String]$TMSession = "Default",

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('TaskId')]
        [Int]$Id,

        [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)]
        [String]$Note,

        [Parameter(Mandatory = $false)]
        [AllowNull()]
        [Alias('Project')]
        [Nullable[Int]]$ProjectId,

        [Parameter(Mandatory = $false)]
        [Bool]$Api = $true
    )

    begin {
        # Get the session configuration
        Write-Verbose "Checking for cached TMSession"
        $TMSessionConfig = $global:TMSessions[$TMSession]
        Write-Debug "TMSessionConfig:"
        Write-Debug ($TMSessionConfig | ConvertTo-Json -Depth 5)
        if (-not $TMSessionConfig) {
            throw "TMSession '$TMSession' not found. Use New-TMSession command before using features."
        }

        # Use the TM session if a project id is not provided
        $ProjectId ??= $TMSessionConfig.UserContext.Project.id
    }

    process {
        if ($TMSessionConfig.TMRestSession -and $Api) {
            Write-Verbose "Using REST API endpoint"
            Write-Verbose "Forming web request parameters"
            $RestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/api/task/$($Id)/addNote"
                Method     = 'POST'
                Body       = (@{
                        note    = $Note
                        project = $ProjectId
                    } | ConvertTo-Json)
                WebSession = $TMSessionConfig.TMRestSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($RestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking REST method"
            try {
                $Response = Invoke-RestMethod @RestSplat
                Write-Debug "Response:"
                Write-Debug ($Response | ConvertTo-Json -Depth 10)
            }
            catch {
                throw "Error while adding task note: $($_.Exception.Message)"
            }
        }
        else {
            Write-Verbose "Using web service endpoint"
            Write-Verbose "Forming web request parameters"
            $WebRequestSplat = @{
                Uri        = "https://$($TMSessionConfig.TMServer)/tdstm/ws/task/$($Id)/addNote"
                Method     = 'POST'
                Body       = (@{
                        note = $Note
                    } | ConvertTo-Json)
                WebSession = $TMSessionConfig.TMWebSession
            }
            Write-Debug "Web Request Parameters:"
            Write-Debug ($WebRequestSplat | ConvertTo-Json -Depth 10)
            Write-Verbose "Invoking web request"
            try {
                $Response = Invoke-WebRequest @WebRequestSplat
                Write-Debug "Response Content:"
                Write-Debug ($Response.Content | ConvertTo-Json -Depth 10)
                if ($Response.StatusCode -notin 200, 204) {
                    throw "Status code $($Response.StatusCode) does not indicate success"
                }
            }
            catch {
                throw "Error while adding task note: $($_.Exception.Message)"
            }
        }
    }
}