functions/MyTasksFunctions.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 |
#region class definition Class MyTask { <# A class to define a task or to-do item #> #Properties # ID and OverDue values are calculated at run time. [int]$ID [string]$Name [string]$Description [datetime]$DueDate [bool]$Overdue [String]$Category [ValidateRange(0, 100)][int]$Progress hidden[bool]$Completed hidden[datetime]$TaskCreated = (Get-Date) hidden[datetime]$TaskModified hidden[guid]$TaskID = (New-Guid) #Methods #set task as completed [void]CompleteTask([datetime]$CompletedDate) { Write-Verbose "[CLASS ] Completing task: $($this.name)" $this.Completed = $True $this.Progress = 100 $this.Overdue = $False $this.TaskModified = $CompletedDate } #check if task is overdue and update hidden [void]Refresh() { Write-Verbose "[CLASS ] Refreshing task $($this.name)" #only mark as overdue if not completed and today is greater than the due date Write-Verbose "[CLASS ] Comparing $($this.DueDate) due date to $(Get-Date)" if ($This.completed) { $this.Overdue = $False } elseif ((Get-Date) -gt $this.DueDate) { $this.Overdue = $True } else { $this.Overdue = $False } } #refresh #Constructors MyTask([string]$Name) { Write-Verbose "[CLASS ] Constructing with name: $name" $this.Name = $Name $this.DueDate = (Get-Date).AddDays(7) $this.TaskModified = (Get-Date) $this.Refresh() } #used for importing from XML MyTask([string]$Name, [datetime]$DueDate, [string]$Description, [string]$Category, [boolean]$Completed) { Write-Verbose "[CLASS ] Constructing with due date, description and category" $this.Name = $Name $this.DueDate = $DueDate $this.Description = $Description $this.Category = $Category $this.TaskModified = $this.TaskCreated $this.Completed = $completed $this.Refresh() } } #end class definition #endregion #region private functions Function _ImportTasks { [cmdletbinding()] Param([string]$Path = $myTaskpath) If (Test-Path $myTaskpath) { [xml]$In = Get-Content -Path $Path -Encoding UTF8 } else { Write-Warning "There are no tasks. Create a new one first." #bail out Break } foreach ($obj in $in.Objects.object) { $obj.Property | ForEach-Object -Begin { $propHash = [ordered]@{} } -Process { $propHash.Add($_.name, $_.'#text') } $propHash | Out-String | Write-Verbose Try { $tmp = New-Object -TypeName MyTask -ArgumentList $propHash.Name, $propHash.DueDate, $propHash.Description, $propHash.Category, $propHash.completed #set additional properties $tmp.TaskID = $prophash.TaskID $tmp.Progress = $prophash.Progress -as [int] $tmp.TaskCreated = $prophash.TaskCreated -as [datetime] $tmp.TaskModified = $prophash.TaskModified -as [datetime] $tmp.Completed = [Convert]::ToBoolean($prophash.Completed) $tmp.refresh() $tmp } Catch { Write-Error $_ } } #foreach } #_ImportTasks #endregion #region exported functions Function New-MyTask { [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Date")] [OutputType("MyTask")] [Alias("nmt", "task")] Param( [Parameter( Position = 0, Mandatory, HelpMessage = "Enter the name of your task", ValueFromPipelineByPropertyName )] [string]$Name, [Parameter(Position = 1, ValueFromPipelineByPropertyName, ParameterSetName = "Date")] [ValidateNotNullorEmpty()] [dateTime]$DueDate = (Get-Date).AddDays(7), [Parameter(ParameterSetName = "Days")] [int]$Days, [Parameter(ValueFromPipelineByPropertyName)] [string]$Description, [switch]$Passthru ) DynamicParam { # Set the dynamic parameters' name $ParameterName = 'Category' # Create the dictionary $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary # Create the collection of attributes $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters' attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $true $ParameterAttribute.ValueFromPipelineByPropertyName = $True $ParameterAttribute.Position = 2 # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) # Generate and set the ValidateSet if (Test-Path -Path $global:myTaskCategory) { $arrSet = Get-Content -Path $global:myTaskCategory | Where-Object { $_ -match "\w+" } | ForEach-Object { $_.Trim() } } else { $arrSet = $script:myTaskDefaultCategories } $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } #Dynamic Param Begin { $Category = $PsBoundParameters[$ParameterName] Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" } Process { #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" Write-Verbose "$((Get-Date).TimeofDay) [PROCESS] Using Parameter set: $($pscmdlet.parameterSetName)" #create the new task Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating new task $Name" If ($Days) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Calculating due date in $Days days" $DueDate = (Get-Date).AddDays($Days) } $task = New-Object -TypeName MyTask -ArgumentList $Name, $DueDate, $Description, $Category, $False #convert to xml Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Converting to XML" $newXML = $task | Select-Object -Property Name, Description, @{Name = 'DueDate'; Expression = { Get-Date -Date $task.DueDate -Format 's' } }, Category, Progress, @{Name = 'TaskCreated'; Expression = { Get-Date -Date $task.TaskCreated -Format 's' } }, @{Name = 'TaskModified'; Expression = { Get-Date -Date $task.TaskModified -Format 's' } }, TaskID, Completed | ConvertTo-Xml Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] $($newXML | Out-String)" #add task to disk via XML file if (Test-Path -Path $mytaskPath) { #import xml file [xml]$in = Get-Content -Path $mytaskPath -Encoding UTF8 #continue of there are existing objects in the file if ($in.objects) { #check if TaskID already exists in file and skip $id = $task.TaskID $result = $in | Select-Xml -XPath "//Object/Property[text()='$id']" if (-Not $result.node) { #if not,import node $imp = $in.ImportNode($newXML.objects.object, $true) #append node $in.Objects.AppendChild($imp) | Out-Null #update file if ($PSCmdlet.ShouldProcess($task.name)) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Saving to existing file" #need to save to a filesystem path # $save = Convert-Path $mytaskPath $in.Save($myTaskPath) } } else { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Skipping $id" } } #if $in.objects } else { #If file doesn't exist create task and save to a file Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Saving first task" #must be an empty XML file if ($PSCmdlet.ShouldProcess($task.name)) { #create an XML declaration section Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating XML declaration" $declare = $newxml.CreateXmlDeclaration("1.0", "UTF-8", "yes") #replace declaration $newXML.ReplaceChild($declare, $newXML.FirstChild) | Out-Null #save the file Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Saving the new file to $myTaskPath" #need to save to a filesystem path # $save = Convert-Path $mytaskPath $newxml.Save($myTaskPath) } } If ($Passthru) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Passing object to the pipeline." (Get-MyTask).where( { $_.taskID -eq $task.taskid }) } } #Process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } #New-MyTask Function Set-MyTask { [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Name")] [OutputType("None", "MyTask")] [Alias("smt")] Param ( [Parameter( ParameterSetName = "Task", ValueFromPipeline)] [MyTask]$Task, [Parameter( Position = 0, Mandatory, HelpMessage = "Enter the name of a task", ParameterSetName = "Name", ValueFromPipelineByPropertyName )] [ValidateNotNullorEmpty()] [string]$Name, [Parameter(ParameterSetName = "ID")] [int]$ID, [string]$NewName, [string]$Description, [datetime]$DueDate, [ValidateRange(0, 100)] [int]$Progress, [switch]$Passthru ) DynamicParam { # Set the dynamic parameters' name $ParameterName = "Category" # Create the dictionary $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary # Create the collection of attributes $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters' attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $False # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) # Generate and set the ValidateSet if (Test-Path -Path $global:myTaskCategory) { $arrSet = Get-Content -Path $global:myTaskCategory -Encoding Unicode | Where-Object { $_ -match "\w+" } | ForEach-Object { $_.Trim() } } else { $arrSet = $script:myTaskDefaultCategories } $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } #Dynamic Param Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Cleaning PSBoundParameters" $PSBoundParameters.Remove("Verbose") | Out-Null $PSBoundParameters.Remove("WhatIf") | Out-Null $PSBoundParameters.Remove("Confirm") | Out-Null $PSBoundParameters.Remove("Passthru") | Out-Null $PSBoundParameters.Remove("ID") | Out-Null } #begin Process { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Using parameter set: $($PSCmdlet.ParameterSetName)" #remove this as a bound parameter $PSBoundParameters.Remove("Task") | Out-Null [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Processing XML" Try { [xml]$In = Get-Content -Path $MyTaskPath -ErrorAction Stop -Encoding UTF8 } Catch { Write-Error "There was a problem loading task data from $myTaskPath." #abort and bail out return } #if using a name get the task from the XML file if ($Name) { $node = ($in | Select-Xml -XPath "//Object/Property[@Name='Name' and contains(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'),'$($name.toLower())')]").Node.ParentNode } else { if ($ID) { #get the task by ID $task = Get-MyTask -ID $ID } $node = ($in | Select-Xml -XPath "//Object/Property[@Name='TaskID' and text()='$($task.taskid)']").Node.ParentNode } if (-Not $Node) { Write-Warning "Failed to find task: $Name" #abort and bail out return } $taskName = $node.SelectNodes("Property[@Name='Name']").'#text' Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Updating task $taskName" Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] $($node.property | Out-String)" #go through all PSBoundParameters other than Name or NewName $PSBoundParameters.keys | Where-Object { $_ -notMatch 'name' } | ForEach-Object { #update the task property Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Updating $_ to $($PSBoundParameters.item($_))" $setting = $node.SelectSingleNode("Property[@Name='$_']") if ($_ -in 'DueDate', 'TaskCreated', 'TaskModified') { $setting.InnerText = Get-Date -Date ($PSBoundParameters.item($_)) -Format 's' } else { $setting.InnerText = $PSBoundParameters.item($_) -as [string] } } If ($NewName) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Updating to new name: $NewName" $node.SelectSingleNode("Property[@Name='Name']").'#text' = $NewName } #update TaskModified $node.SelectSingleNode("Property[@Name='TaskModified']").'#text' = (Get-Date -Format 's').ToString() If ($PSCmdlet.ShouldProcess($TaskName)) { #update source Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Saving task file" #need to save to a filesystem path #$save = Convert-Path $mytaskPath $in.Save($mytaskpath) #pass object to the pipeline if ($Passthru) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Passing object to the pipeline" Get-MyTask -Name $taskName } } #should process } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } #Set-MyTask Function Remove-MyTask { [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Name")] [OutputType("None")] [Alias("rmt")] Param( [Parameter( Position = 0, Mandatory, HelpMessage = "Enter task name", ParameterSetName = "Name" )] [ValidateNotNullorEmpty()] [string]$Name, [Parameter( Position = 0, Mandatory, HelpMessage = "Enter a task ID number", ParameterSetName = "ID" )] [int]$ID, [Parameter( Position = 0, Mandatory, ValueFromPipeline, ParameterSetName = "Object" )] [ValidateNotNullorEmpty()] [MyTask]$InputObject ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" if ($PSCmdlet.ShouldProcess($myTaskPath, "Create backup")) { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Creating a backup copy of $myTaskPath" Backup-MyTaskFile } #load tasks from XML Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Loading tasks from XML" [xml]$In = Get-Content -Path $MyTaskPath -Encoding UTF8 } #begin Process { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Using parameter set: $($PSCmdlet.parameterSetname)" Switch ($pscmdlet.ParameterSetName) { "Name" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving task: $Name" Try { $taskID = (Get-MyTask -Name $Name -ErrorAction Stop).TaskID } Catch { Write-Warning "Failed to find a task with a name of $Name" Write-Warning $_.exception.message #abort and bail out return } } #Name "ID" { $TaskID = (Get-MyTask -ID $ID).TaskID if (-Not $TaskID) { #bail out return } } #ID "Object" { $TaskID = $InputObject.TaskID } } #select node by TaskID (GUID) Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Identifying task id: $TaskID" $node = ($in | Select-Xml -XPath "//Object/Property[text()='$TaskID']").node.ParentNode if ($node) { #remove it Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Removing: $($node.Property | Out-String)" if ($PSCmdlet.ShouldProcess($TaskID)) { $node.parentNode.RemoveChild($node) | Out-Null $node.ParentNode.objects #save file Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Updating $MyTaskPath" #need to save to a filesystem path # $save = Convert-Path $mytaskPath $in.Save($mytaskpath) } #should process } else { Write-Warning "Failed to find a matching task with an id of $TaskID" Return } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } #Remove-MyTask Function Get-MyTask { [cmdletbinding(DefaultParameterSetName = "Days")] [OutputType("MyTask")] [Alias("gmt","shmt","Show-MyTask")] Param( [Parameter( Position = 0, ParameterSetName = "Name" )] [string]$Name, [Parameter(ParameterSetName = "ID")] [int[]]$ID, [Parameter(ParameterSetName = "All")] [switch]$All, [Parameter(ParameterSetName = "Completed")] [switch]$Completed, [Parameter(ParameterSetName = "Days")] [int]$DaysDue = 30 ) DynamicParam { # Set the dynamic parameters' name $ParameterName = "Category" # Create the dictionary $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary # Create the collection of attributes $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters' attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $False $ParameterAttribute.ParameterSetName = "Category" # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) # Generate and set the ValidateSet if (Test-Path -Path $global:myTaskCategory) { $arrSet = Get-Content -Path $global:myTaskCategory | Where-Object { $_ -match "\w+" } | ForEach-Object { $_.Trim() } } else { $arrSet = $script:myTaskDefaultCategories } $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($MyInvocation.Mycommand)" $Category = $PsBoundParameters[$ParameterName] Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Using parameter set $($PSCmdlet.ParameterSetName)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" #import from the XML file Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Importing tasks from $mytaskPath" $tasks = _ImportTasks | Sort-Object -Property DueDate Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Imported $($tasks.count) tasks" } Process { #initialize counter $counter = 0 foreach ($task in $tasks ) { $counter++ $task.ID = $counter } Switch ($PSCmdlet.ParameterSetName) { "Name" { if ($Name -match "\w+") { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving task: $Name" $results = $tasks.Where( { $_.Name -like $Name }) } else { #write all tasks to the pipeline Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving all incomplete tasks" $results = $tasks.Where( { -Not $_.Completed }) } } #name "ID" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving Task by ID: $ID" #$results = $tasks.where( {$_.id -eq $ID}) $results = $tasks.where( { $_.id -match "^($($id -join '|'))$" }) } #id "All" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving all tasks" $results = $Tasks } #all "Completed" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving completed tasks" $results = $tasks.Where( { $_.Completed }) } #completed "Category" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving tasks for category $Category" $results = $tasks.Where( { $_.Category -eq $Category -AND (-Not $_.Completed) }) } #category "Days" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving tasks due in $DaysDue days or before" $results = $tasks.Where( { ($_.DueDate -le (Get-Date).AddDays($DaysDue)) -AND (-Not $_.Completed) }) } } #switch #display tasks if found otherwise display a warning if ($results.count -ge 1) { $results } else { Write-Warning "No tasks found matching your criteria" } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($MyInvocation.Mycommand)" } #end } #Get-MyTask Function Complete-MyTask { [cmdletbinding(SupportsShouldProcess, DefaultParameterSetName = "Name")] [OutputType("None", "MyTask")] [Alias("cmt")] Param ( [Parameter( ParameterSetName = "Task", ValueFromPipeline)] [MyTask]$Task, [Parameter( Position = 0, Mandatory, HelpMessage = "Enter the name of a task", ParameterSetName = "Name" )] [ValidateNotNullorEmpty()] [string]$Name, [Parameter( Mandatory, HelpMessage = "Enter the task ID", ParameterSetName = "ID" )] [int32]$ID, [datetime]$CompletedDate = $(Get-Date), [switch]$Archive, [switch]$Passthru ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundParameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" } #begin Process { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Using parameter set: $($PSCmdlet.ParameterSetName)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] PSBoundParameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" if ($Name) { #get the task Try { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving task: $Name" $Task = Get-MyTask -Name $Name -ErrorAction Stop } Catch { Write-Error $_ #bail out Return } } elseif ($ID) { #get the task Try { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving task ID: $ID" $Task = Get-MyTask -ID $ID -ErrorAction Stop } Catch { Write-Error $_ #bail out Return } } If ($Task) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Marking task as completed" #invoke CompleteTask() method $task.CompleteTask($CompletedDate) Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] $($task | Select-Object *,Completed,TaskModified,TaskID | Out-String)" #find matching XML node and replace it Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Updating task file" #convert current task to XML $new = ($task | Select-Object -Property Name, Description, @{Name = 'DueDate'; Expression = { Get-Date -Date $task.DueDate -Format 's' } }, Category, Progress, @{Name = 'TaskCreated'; Expression = { Get-Date -Date $task.TaskCreated -Format 's' } }, @{Name = 'TaskModified'; Expression = { Get-Date -Date $task.TaskModified -Format 's' } }, TaskID, Completed | ConvertTo-Xml).Objects.Object #load tasks from XML [xml]$In = Get-Content -Path $MyTaskPath -Encoding UTF8 #select node by TaskID (GUID) $node = ($in | Select-Xml -XPath "//Object/Property[text()='$($task.TaskID)']").node.ParentNode #import the new node $imp = $in.ImportNode($new, $true) #replace node $node.ParentNode.ReplaceChild($imp, $node) | Out-Null #save If ($PSCmdlet.ShouldProcess($task.name)) { #$save = Convert-Path $mytaskPath $in.Save($mytaskpath) if ($Archive) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Archiving completed task" Save-MyTask -Task $Task } if ($Passthru) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Passing task back to the pipeline" Get-MyTask -Name $task.name } } } else { Write-Warning "Failed to find a matching task." } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } #Complete-MyTask Function Get-MyTaskCategory { [cmdletbinding()] [OutputType([System.String])] Param() Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" } #begin Process { If (Test-Path -Path $global:myTaskCategory) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving user categories from $global:myTaskCategory" Get-Content -Path $global:myTaskCategory -Encoding Unicode | Where-Object { $_ -match "\w+" } } else { #Display the defaults Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving module default categories" $script:myTaskDefaultCategories } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } Function Add-MyTaskCategory { [cmdletbinding(SupportsShouldProcess)] [OutputType("None")] Param( [Parameter( Position = 0, Mandatory, HelpMessage = "Enter a new task category", ValueFromPipeline )] [ValidateNotNullorEmpty()] [string[]]$Category ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #test if user category file already exists and if not, then #create it if (-Not (Test-Path -Path $global:myTaskCategory)) { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Creating new user category file $global:myTaskCategory" Set-Content -Value $script:myTaskDefaultCategories -Path $global:myTaskCategory -Encoding Unicode } #get current contents $current = Get-Content -Path $global:myTaskCategory -Encoding Unicode | Where-Object { $_ -match "\w+" } } #begin Process { foreach ($item in $Category) { if ($current -contains $($item.trim())) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Skipping duplicate item $item" } else { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Adding $item" Add-Content -Value $item.Trim() -Path $global:myTaskCategory -Encoding Unicode } } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } Function Remove-MyTaskCategory { [cmdletbinding(SupportsShouldProcess)] [OutputType("None")] Param( [Parameter( Position = 0, Mandatory, HelpMessage = "Enter a task category to remove", ValueFromPipeline )] [ValidateNotNullorEmpty()] [string[]]$Category ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #get current contents $current = Get-Content -Path $global:myTaskCategory -Encoding Unicode | Where-Object { $_ -match "\w+" } #create backup $back = Join-Path -Path $mytaskhome -ChildPath MyTaskCategory.bak Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Creating backup copy" Copy-Item -Path $global:myTaskCategory -Destination $back -Force } #begin Process { foreach ($item in $Category) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Removing category $item" $current = ($current).Where( { $_ -notcontains $item }) } } #process End { #update file Write-Verbose "[$((Get-Date).TimeofDay) END ] Updating: $global:myTaskCategory" Set-Content -Value $current -Path $global:myTaskCategory -Encoding Unicode Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } #create a backup copy of task xml file Function Backup-MyTaskFile { [cmdletbinding(SupportsShouldProcess)] [OutputType("None", "System.IO.FileInfo")] Param( [Parameter( Position = 0, HelpMessage = "Enter the filename and path for the backup xml file" )] [ValidateNotNullorEmpty()] [string]$Destination = (Join-Path -Path $mytaskhome -ChildPath "MyTasks_Backup_$(Get-Date -Format "yyyyMMdd").xml" ), [switch]$Passthru ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Creating backup file $Destination" #add MyTaskPath to PSBoundparameters so it can be splatted to Copy-Item $PSBoundParameters.Add("Path", $myTaskPath) #explicitly add Destination if not already part of PSBoundParameters if (-Not ($PSBoundParameters.ContainsKey("Destination"))) { $PSBoundParameters.Add("Destination", $Destination) } } #begin Process { If (Test-Path -Path $myTaskPath) { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Copy parameters" Write-Verbose ($PSBoundParameters | Format-List | Out-String) Copy-Item @psBoundParameters Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Adding comment to backup XML file" #insert a comment into the XML file [xml]$doc = Get-Content -Path $Destination -Encoding UTF8 $comment = $doc.CreateComment("Backup of $MytaskPath created on $(Get-Date)") $doc.InsertAfter($comment, $doc.FirstChild) | Out-Null $doc.Save($Destination) } else { Write-Warning "Failed to find $myTaskPath" } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } #end } #archive completed tasks Function Save-MyTask { [cmdletbinding(SupportsShouldProcess)] [OutputType("None", "myTask")] [Alias("Archive-MyTask")] Param( [Parameter(Position = 0)] [ValidateNotNullorEmpty()] [string]$Path = $myTaskArchivePath, [Parameter(ValueFromPipeline)] [ValidateNotNullorEmpty()] [MyTask[]]$Task, [switch]$Passthru ) Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting: $($MyInvocation.Mycommand)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) EGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Using parameter set $($PSCmdlet.ParameterSetName)" } Process { [xml]$In = Get-Content -Path $mytaskPath -Encoding UTF8 if ($Task) { $taskID = $task.TaskID Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Archiving task $($task.name) [$($task.taskID)]" $completed = $in.Objects | Select-Xml -XPath "//Object/Property[text()='$taskID']" } else { #get completed tasks Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Getting completed tasks" $completed = $In.Objects | Select-Xml -XPath "//Property[@Name='Completed' and text()='True']" } if ($completed) { #save to $myTaskArchivePath if (Test-Path -Path $Path) { #append to existing document Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Appending to $Path" [xml]$Out = Get-Content -Path $Path -Encoding UTF8 $parent = $Out.Objects } else { #create a new document Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Creating $Path" $out = [xml]::new() $ver = $out.CreateXmlDeclaration("1.0", "UTF-8", $null) $out.AppendChild($ver) | Out-Null $objects = $out.CreateNode("element", "Objects", $null) $parent = $out.AppendChild($objects) } #import foreach ($node in $completed.node) { $imp = $out.ImportNode($node.ParentNode, $True) Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Archiving $($node.parentnode.property[0].'#text')" if ($PSCmdlet.ShouldProcess( $($node.parentnode.property[0].'#text') , "Archiving")) { $parent.AppendChild($imp) | Out-Null #remove from existing file $in.objects.RemoveChild($node.parentnode) | Out-Null } } Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Saving $Path" if ($PSCmdlet.ShouldProcess($Path)) { $out.Save($Path) #save task file after saving archive #need to save to a filesystem path #$save = Convert-Path $mytaskPath $in.Save($mytaskpath) If ($Passthru) { Get-Item -Path $Path } } } else { Write-Host "Didn't find any completed tasks." -ForegroundColor Magenta } } #Process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending: $($MyInvocation.Mycommand)" } } Function Set-MyTaskHome { [cmdletbinding(SupportsShouldProcess)] [alias("Set-MyTaskPath")] [OutputType("None", [System.Management.Automation.PSVariable])] Param( [Parameter(Mandatory, HelpMessage = "Enter the path to your new myTaskHome directory")] [ValidateScript( { Test-Path $_ })] [string]$Path, [switch]$Passthru ) If ($pscmdlet.ShouldProcess("$path", "Update task path")) { $global:mytaskhome = Convert-Path $Path #path to the category file $global:myTaskCategory = Join-Path -Path $mytaskhome -ChildPath myTaskCategory.txt #path to stored tasks $global:mytaskPath = Join-Path -Path $mytaskhome -ChildPath myTasks.xml #path to archived or completed tasks $global:myTaskArchivePath = Join-Path -Path $mytaskhome -ChildPath myTasksArchive.xml if ($passthru) { Get-Variable myTaskHome, myTaskPath, myTaskArchivePath, myTaskCategory } } } #close Set-MyTaskPath Function Get-MyTaskHome { [cmdletbinding()] [Alias("Get-MyTaskPath")] Param() [PSCustomObject]@{ PSTypeName = "myTaskPath" myTaskHome = $global:mytaskhome myTaskPath = $global:myTaskPath myTaskArchivePath = $global:myTaskArchivePath myTaskCategory = $global:myTaskCategory } } Function Get-MyTaskArchive { [cmdletbinding(DefaultParameterSetName = "Name")] [OutputType("MyTaskArchive")] Param( [Parameter( Position = 0, ParameterSetName = "Name" )] [string]$Name ) DynamicParam { # Set the dynamic parameters' name $ParameterName = "Category" # Create the dictionary $RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary # Create the collection of attributes $AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute] # Create and set the parameters' attributes $ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute $ParameterAttribute.Mandatory = $False $ParameterAttribute.ParameterSetName = "Category" # Add the attributes to the attributes collection $AttributeCollection.Add($ParameterAttribute) # Generate and set the ValidateSet if (Test-Path -Path $global:myTaskCategory) { $arrSet = Get-Content -Path $global:myTaskCategory | Where-Object { $_ -match "\w+" } | ForEach-Object { $_.Trim() } } else { $arrSet = $script:myTaskDefaultCategories } $ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet) # Add the ValidateSet to the attributes collection $AttributeCollection.Add($ValidateSetAttribute) # Create and return the dynamic parameter $RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection) $RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter) return $RuntimeParameterDictionary } Begin { Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Starting $($MyInvocation.Mycommand)" $Category = $PsBoundParameters[$ParameterName] Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Using parameter set $($PSCmdlet.ParameterSetName)" #display PSBoundparameters formatted nicely for Verbose output [string]$pb = ($PSBoundParameters | Format-Table -AutoSize | Out-String).TrimEnd() Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] PSBoundparameters: `n$($pb.split("`n").Foreach({"$("`t"*4)$_"}) | Out-String) `n" #import from the XML file Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Importing tasks from $mytaskPath" $tasks = _ImportTasks -Path $myTaskArchivePath | Sort-Object -Property { $_.TaskModified -as [datetime] } Write-Verbose "[$((Get-Date).TimeofDay) BEGIN ] Imported $($tasks.count) tasks" } Process { #initialize counter $counter = 0 foreach ($task in $tasks ) { $counter++ $task.ID = $counter } Switch ($PSCmdlet.ParameterSetName) { "Name" { if ($Name -match "\w+") { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving task: $Name" $results = $tasks.Where( { $_.Name -like $Name }) } else { #write all tasks to the pipeline Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving all tasks" $results = $tasks } } #name "Category" { Write-Verbose "[$((Get-Date).TimeofDay) PROCESS] Retrieving tasks for category $Category" $results = $tasks.Where( { $_.Category -eq $Category }) } #category } #switch #display tasks if found otherwise display a warning if ($results.count -ge 1) { $results.foreach( { $_.psobject.typenames.insert(0, "myTaskArchive") }) $results } else { Write-Warning "No tasks found matching your criteria" } } #process End { Write-Verbose "[$((Get-Date).TimeofDay) END ] Ending $($MyInvocation.Mycommand)" } #end } #Get-MyTask #endregion |