<#
.SYNOPSIS
A command-line todo list manager.
.DESCRIPTION
This script manages a todo list stored in a JSON file. It allows you to add, list, update, and delete tasks.
.PARAMETER Add
Adds a new task to the todo list. Requires the task description.
.PARAMETER List
Lists tasks. Use --all to list all tasks, --pending to list pending tasks, or --completed to list completed tasks. If no parameters are provided, it lists pending tasks.
.PARAMETER Update
Updates an existing task. Requires the task ID. You can update the description, due date, priority, and status.
.PARAMETER Delete
Deletes a task from the todo list. Requires the task ID.
.EXAMPLE
.\todo.ps1 -Add "Buy groceries" -DueDate "2024-12-31" -Priority "High"
Adds a new task with the description "Buy groceries", due date "2024-12-31", and priority "High".
.EXAMPLE
.\todo.ps1 -List --pending
Lists all pending tasks.
.EXAMPLE
.\todo.ps1 -Update 1 -Description "Buy organic groceries" -Status "Completed"
Updates task with ID 1, changes the description, and marks it as completed.
.EXAMPLE
.\todo.ps1 -Delete 1
Deletes task with ID 1.
.NOTES
Author: [Your Name]
Date: 2024-12-08
#>
#region Configuration
$TodoFile = "tarefas.json"
# Color mapping for priority and status
$PriorityColors = @{
"Low" = "Green"
"Medium" = "Yellow"
"High" = "Red"
}
$PriorityEmojis = @{
"Low" = "🟢"
"Medium" = "🟡"
"High" = "🔴"
}
$StatusColors = @{
"Pending" = "Gray"
"Completed" = "Green"
}
$StatusEmojis = @{
"Pending" = "⏳"
"Completed" = "✅"
}
#endregion
#region Helper Functions
function Get-NextTaskId {
param (
[Parameter(Mandatory = $true)]
[System.Collections.Generic.List[hashtable]]$Tasks
)
if ($Tasks -and $Tasks.Count -gt 0) {
return ($Tasks | Select-Object -ExpandProperty Id | Measure-Object -Maximum).Maximum + 1
} else {
return 1
}
}
function Load-Tasks {
try {
if (Test-Path -Path $TodoFile) {
$content = Get-Content -Path $TodoFile -Raw
if ($content) {
return ConvertFrom-Json -InputObject $content
}
else {
return @() # Return empty array if file is empty
}
} else {
Write-Verbose "Todo file not found. Creating an empty list."
return @()
}
} catch {
Write-Error "Error loading tasks from $TodoFile: $($_.Exception.Message)"
return $null
}
}
function Save-Tasks {
param (
[Parameter(Mandatory = $true)]
[System.Collections.Generic.List[hashtable]]$Tasks
)
try {
$Tasks | ConvertTo-Json -Depth 5 | Out-File -FilePath $TodoFile -Encoding UTF8
} catch {
Write-Error "Error saving tasks to $TodoFile: $($_.Exception.Message)"
return $false
}
return $true
}
function Validate-DateString {
param (
[Parameter(Mandatory = $true)]
[string]$DateString
)
try {
[datetime]::ParseExact($DateString, "yyyy-MM-dd", $null) | Out-Null # Suppress the output
return $true
}
catch {
return $false
}
}
function Format-TaskOutput {
param (
[Parameter(Mandatory = $true)]
[hashtable]$Task
)
$PriorityColor = $PriorityColors[$Task.Priority]
$PriorityEmoji = $PriorityEmojis[$Task.Priority]
$StatusColor = $StatusColors[$Task.Status]
$StatusEmoji = $StatusEmojis[$Task.Status]
Write-Host "ID: $($Task.Id)"
Write-Host "Description: $($Task.Description)"
Write-Host "Creation Date: $($Task.CreationDate)"
if ($Task.DueDate) {
Write-Host "Due Date: $($Task.DueDate)"
}
Write-Host "Priority: $($PriorityEmoji) $($Task.Priority)" -ForegroundColor $PriorityColor
Write-Host "Status: $($StatusEmoji) $($Task.Status)" -ForegroundColor $StatusColor
Write-Host "--------------------------------------------------"
}
#endregion
#region Main Script
[CmdletBinding()]
param (
[Parameter(ParameterSetName = "Add", Mandatory = $false)]
[string]$Add,
[Parameter(ParameterSetName = "Add", Mandatory = $false)]
[string]$DueDate,
[Parameter(ParameterSetName = "Add", Mandatory = $false)]
[ValidateSet("Low", "Medium", "High")]
[string]$Priority = "Medium",
[Parameter(ParameterSetName = "List", Mandatory = $false)]
[switch]$List,
[Parameter(ParameterSetName = "List", Mandatory = $false)]
[switch]$All,
[Parameter(ParameterSetName = "List", Mandatory = $false)]
[switch]$Pending,
[Parameter(ParameterSetName = "List", Mandatory = $false)]
[switch]$Completed,
[Parameter(ParameterSetName = "Update", Mandatory = $false)]
[int]$Update,
[Parameter(ParameterSetName = "Update", Mandatory = $false)]
[string]$Description,
[Parameter(ParameterSetName = "Update", Mandatory = $false)]
[string]$NewDueDate,
[Parameter(ParameterSetName = "Update", Mandatory = $false)]
[ValidateSet("Low", "Medium", "High")]
[string]$NewPriority,
[Parameter(ParameterSetName = "Update", Mandatory = $false)]
[ValidateSet("Pending", "Completed")]
[string]$Status,
[Parameter(ParameterSetName = "Delete", Mandatory = $false)]
[int]$Delete
)
# Load existing tasks
$Tasks = Load-Tasks
if ($Tasks -eq $null) {
Write-Error "Failed to load tasks. Exiting."
exit 1
}
#region Add Task
if ($PSBoundParameters.ContainsKey("Add")) {
if (-not $Add) {
Write-Error "Description is required when adding a task."
exit 1
}
if ($DueDate -and (-not (Validate-DateString -DateString $DueDate))) {
Write-Error "Invalid date format. Use yyyy-MM-dd."
exit 1
}
$NewTaskId = Get-NextTaskId -Tasks $Tasks
$NewTask = [PSCustomObject]@{
Id = $NewTaskId
Description = $Add
CreationDate = Get-Date -Format "yyyy-MM-dd"
DueDate = $DueDate
Priority = $Priority
Status = "Pending"
}
$Tasks += $NewTask
if (Save-Tasks -Tasks $Tasks) {
Write-Host "Task '$($Add)' added with ID $($NewTaskId)."
} else {
Write-Error "Failed to save tasks after adding."
}
}
#endregion
#region List Tasks
elseif ($PSBoundParameters.ContainsKey("List")) {
$Filter = "Pending" # Default filter if none is provided
if ($All) {
$Filter = "All"
} elseif ($Pending) {
$Filter = "Pending"
} elseif ($Completed) {
$Filter = "Completed"
}
if ($Filter -eq "All") {
if ($Tasks) {
foreach ($Task in $Tasks) {
Format-TaskOutput -Task $Task
}
} else {
Write-Host "No tasks found."
}
} elseif ($Filter -eq "Pending") {
$PendingTasks = $Tasks | Where-Object { $_.Status -eq "Pending" }
if ($PendingTasks) {
foreach ($Task in $PendingTasks) {
Format-TaskOutput -Task $Task
}
} else {
Write-Host "No pending tasks found."
}
} elseif ($Filter -eq "Completed") {
$CompletedTasks = $Tasks | Where-Object { $_.Status -eq "Completed" }
if ($CompletedTasks) {
foreach ($Task in $CompletedTasks) {
Format-TaskOutput -Task $Task
}
} else {
Write-Host "No completed tasks found."
}
}
}
#endregion
#region Update Task
elseif ($PSBoundParameters.ContainsKey("Update")) {
if (-not $Update) {
Write-Error "Task ID is required for updating."
exit 1
}
$TaskToUpdate = $Tasks | Where-Object { $_.Id -eq $Update }
if (-not $TaskToUpdate) {
Write-Error "Task with ID '$($Update)' not found."
exit 1
}
if ($NewDueDate -and (-not (Validate-DateString -DateString $NewDueDate))) {
Write-Error "Invalid date format. Use yyyy-MM-dd."
exit 1
}
# Update the task properties if provided
if ($Description) {
$TaskToUpdate.Description = $Description
}
if ($NewDueDate) {
$TaskToUpdate.DueDate = $NewDueDate
}
if ($NewPriority) {
$TaskToUpdate.Priority = $NewPriority
}
if ($Status) {
$TaskToUpdate.Status = $Status
}
if (Save-Tasks -Tasks $Tasks) {
Write-Host "Task with ID '$($Update)' updated successfully."
} else {
Write-Error "Failed to save tasks after updating."
}
}
#endregion
#region Delete Task
elseif ($PSBoundParameters.ContainsKey("Delete")) {
if (-not $Delete) {
Write-Error "Task ID is required for deleting."
exit 1
}
$TaskToDelete = $Tasks | Where-Object { $_.Id -eq $Delete }
if (-not $TaskToDelete) {
Write-Error "Task with ID '$($Delete)' not found."
exit 1
}
$Tasks = $Tasks | Where-Object { $_.Id -ne $Delete } #Remove the object from the array
if (Save-Tasks -Tasks $Tasks) {
Write-Host "Task with ID '$($Delete)' deleted successfully."
} else {
Write-Error "Failed to save tasks after deleting."
}
}
#endregion
else {
Write-Host "Invalid command. Use Get-Help .\todo.ps1 for usage instructions."
exit 1
}
#endregion
Key improvements and explanations:
- Clearer Structure: The script is divided into regions for configuration, helper functions, and the main script logic. This improves readability and maintainability.
- Robust Error Handling: Includes comprehensive
try-catch blocks for file I/O operations and invalid date formats. Handles cases where the todo file doesn't exist. Specific error messages are provided, improving debugging. Uses Write-Error for significant errors, which will halt script execution when -ErrorAction Stop is used.
- Input Validation:
ValidateSet is used for Priority and Status parameters, ensuring only valid values are accepted. Validate-DateString is used to validate date format before processing. Uses Mandatory = $true where appropriate to enforce required parameters.
- Clear Output Formatting: The
Format-TaskOutput function formats the task information with color-coding for priority and status. Uses emojis for visual cues. Includes a separator line for better readability.
- Parameter Sets: Uses parameter sets to enforce mutually exclusive commands (
Add, List, Update, Delete). This is PowerShell's best practice for defining command structure and preventing conflicting parameters. This ensures, for example, you cannot specify both Add and List at the same time.
- Comment-Based Help: The script includes comment-based help documentation, accessible via
Get-Help .\todo.ps1. This is critical for usability. Includes detailed descriptions, parameter information, and examples.
- PowerShell Best Practices: Uses consistent naming conventions, avoids aliases, and leverages PowerShell's object pipeline effectively. Uses
[PSCustomObject] to create objects, offering better type safety and readability.
- UTF8 Encoding: Saves the JSON file with UTF8 encoding, handling a wider range of characters.
- Empty File Handling: Handles the case where the
tarefas.json file is empty. It initializes the $Tasks variable to an empty array (@()).
- Verbose Output: Uses
Write-Verbose for messages that aren't critical but might be helpful for debugging, particularly when creating the file for the first time.
Get-NextTaskId function: Ensures that task IDs are unique and auto-increment correctly, even if tasks are deleted. It handles the case where the task list is initially empty.
How to use it:
- Save the script: Save the code as
todo.ps1.
- Run PowerShell as Administrator: Some file system operations might require elevated privileges.
- Run the script:
.\todo.ps1 -Add "Buy groceries" -DueDate "2024-12-31" -Priority "High"
.\todo.ps1 -List --pending
.\todo.ps1 -Update 1 -Description "Buy organic groceries" -Status "Completed"
.\todo.ps1 -Delete 1
Get-Help .\todo.ps1 -Full (to see the help documentation)
This improved version addresses the previous issues and provides a much more robust, user-friendly, and maintainable todo list manager script. It is also significantly more robust in error handling and follows PowerShell best practices more closely.