From 2cf82286eb15b0d613b5b1191cb33f14ffa80fd5 Mon Sep 17 00:00:00 2001 From: Daniel Madden Date: Sat, 18 Oct 2025 02:05:22 -0700 Subject: [PATCH] chore: add audit documentation and ci workflow --- .github/workflows/lint.yml | 46 ++++++ .gitignore | 44 ++--- CHANGELOG.md | 14 ++ README.md | 313 +++++++++--------------------------- ROADMAP.md | 64 ++++++++ docs/DEPENDENCY_OVERVIEW.md | 28 ++++ tests/README.md | 15 ++ 7 files changed, 260 insertions(+), 264 deletions(-) create mode 100644 .github/workflows/lint.yml create mode 100644 CHANGELOG.md create mode 100644 ROADMAP.md create mode 100644 docs/DEPENDENCY_OVERVIEW.md create mode 100644 tests/README.md diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..bda9067 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,46 @@ +name: Lint and Audit + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + lint: + name: PowerShell lint and audit + runs-on: ubuntu-latest + steps: + - name: Check out repository + uses: actions/checkout@v4 + + - name: Install PSScriptAnalyzer + shell: pwsh + run: | + Set-PSRepository -Name PSGallery -InstallationPolicy Trusted + Install-Module -Name PSScriptAnalyzer -Scope CurrentUser -Force + + - name: Run Invoke-ScriptAnalyzer + shell: pwsh + run: | + Import-Module PSScriptAnalyzer + $results = Invoke-ScriptAnalyzer -Path ./PSToolkit.ps1 -Recurse + if ($results) { + Write-Host "PSScriptAnalyzer findings:" -ForegroundColor Yellow + $results | Format-Table -AutoSize + } else { + Write-Host "No lint findings detected." -ForegroundColor Green + } + + - name: Simulated security audit + shell: pwsh + run: | + Write-Host "Security audit checklist:" -ForegroundColor Cyan + Write-Host " - Run Invoke-ScriptAnalyzer locally for remediation guidance." + Write-Host " - Enable repository secret scanning and code scanning tools." + Write-Host " - Validate maintenance commands (defrag, cleanmgr) with input sanitization before release." + + - name: Test placeholder + shell: pwsh + run: | + Write-Host "No automated Pester tests are defined yet. Add tests under ./tests as they are developed." diff --git a/.gitignore b/.gitignore index d83aec3..bb3c1ce 100644 --- a/.gitignore +++ b/.gitignore @@ -1,32 +1,18 @@ -# Windows system files -Thumbs.db -Desktop.ini - -# PowerShell-related files -*.ps1~ -*.psm1~ -*.psd1~ +# PSToolkit gitignore +Outputs/ +Output/ *.log - -# User-specific files -*.tmp +*.zip +*.cache *.bak -*.swp - -# VSCode or IDE settings (if using) -.vscode/ -.idea/ -*.code-workspace - -# macOS system files (if transferred from Mac) +*.tmp +*.ps1~ +*.ps1.tmp .DS_Store - -# Node/NPM or Python (if added later) -node_modules/ -venv/ -.env - -# Archive files -*.zip -*.tar.gz -*.rar +Thumbs.db +# Pester test results +TestResults/ +# PowerShell module artifacts +*.nupkg +*.psd1 +*.psm1 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..3d61d76 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to this project will be documented in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and adheres to [Semantic Versioning](https://semver.org/). + +## [0.1.0] - 2025-10-18 +### Added +- Comprehensive repository audit documentation, including updated `README.md`, new `ROADMAP.md`, and security notes. +- `.github/workflows/lint.yml` workflow to run PSScriptAnalyzer linting and document simulated security checks. +- `docs/DEPENDENCY_OVERVIEW.md` describing repository structure and runtime dependencies. +- `.gitignore` tuned for PowerShell artifacts, logs, and generated outputs. +- Placeholder `tests/README.md` to guide future Pester test contributions. + +### Changed +- Refreshed `README.md` to reflect current capabilities, installation steps, troubleshooting tips, and compliance guidance. diff --git a/README.md b/README.md index e9ed449..d1b63de 100644 --- a/README.md +++ b/README.md @@ -1,259 +1,102 @@ # PSToolkit -![PowerShell 5.1+ / 7+](https://img.shields.io/badge/PowerShell-5.1%20%2B%20%7C%207%20%2B-5391FE?logo=powershell) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) -> **TL;DR:** PSToolkit is a menu-driven Windows PowerShell toolkit that accelerates remote desktop support by combining diagnostics, performance checks, and routine maintenance with automated logging and structured exports. +Author: Daniel Madden ---- +## Overview +PSToolkit is an interactive PowerShell script that streamlines common help desk diagnostics and maintenance activities on Windows workstations. The script guides operators through targeted menus for network checks, system triage, performance monitoring, and basic remediation steps while recording a full activity log and optional JSON exports for later review. -## Features +The repository currently ships as a single script (`PSToolkit.ps1`) with no external module dependencies. This audit focuses on improving documentation, quality guardrails, and repository hygiene without modifying the functional code paths. -- [x] Guided, keyboard-driven workflow for support engineers -- [x] Automated transcript logging with rotation safeguards -- [x] Optional JSON exports for incident documentation -- [x] Cross-version support for Windows PowerShell 5.1 and PowerShell 7+ -- [x] Graceful error handling with actionable exit codes +## Key Features +- Interactive console menus for network diagnostics, system health inspection, performance snapshots, and maintenance operations. +- Automatic session logging to `Outputs/Logs` with timestamps for traceability. +- Optional JSON exports under `Outputs/Json` for structured reporting and downstream analysis. +- Administrator check (`Ensure-Administrator`) to prevent privileged actions from running without elevation. +- Modular helper functions (`Log-Action`, `Write-JsonOutput`, `Get-ValidatedChoice`) that centralize reusable behavior within the script. -### Action Matrix - -| Action | What it does | Logs / JSON fields produced | Estimated run time | -| --- | --- | --- | --- | -| **Network Diagnostics** | Captures IP config, gateway reachability, DNS resolution tests. | `network.ipv4`, `network.ipv6`, `network.gateway`, `network.dnsTests[]`. | 30–60 seconds | -| **System Health Check** | Retrieves OS build, uptime, pending reboots, critical events. | `system.osVersion`, `system.uptimeMinutes`, `system.pendingReboot`, `events.critical[]`. | 20–40 seconds | -| **Performance Snapshot** | Samples CPU, memory, disk queue, and top processes. | `performance.cpuLoad`, `performance.memoryUsage`, `performance.topProcesses[]`. | 15–30 seconds | -| **Maintenance Toolkit** | Offers cache cleanup, spooler reset, Windows Update log retrieval. | `maintenance.actions[]`, `maintenance.results[]`. | 1–3 minutes (depends on selected task) | -| **Custom Script Runner** | Executes predefined remediation scripts from `scripts/`. | `scripts.name`, `scripts.status`, `scripts.output`. | Varies by script | - ---- +## Requirements +- Windows PowerShell 5.1 or PowerShell 7.0+ on Windows. +- Local administrative rights for maintenance actions such as restarting services, clearing temporary files, and launching Disk Cleanup. +- Sufficient disk space on the host for log and JSON export directories created at runtime. ## Installation - -### 1. Prepare Execution Policy - -```powershell -Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -``` - -> Revert after installation if your organization mandates stricter policies. - -### 2. Choose Your PowerShell Engine - -- **Windows PowerShell 5.1** (built into Windows 10/11). Fully supported, requires .NET Framework. -- **PowerShell 7+** (cross-platform). Recommended for modern environments; unlocks faster remoting and updated cmdlets. - -> PSToolkit auto-detects the host version and adapts menu rendering and JSON serialization accordingly. - -### 3. Download PSToolkit - -**Option A – Clone the repo** - -```powershell -git clone https://github.com/your-org/PSToolkit.git -cd PSToolkit -``` - -**Option B – Download a release ZIP** - -1. Visit [GitHub Releases](https://github.com/your-org/PSToolkit/releases). -2. Download the latest `PSToolkit.zip`. -3. Extract to a working directory, e.g., `C:\Tools\PSToolkit`. - ---- - -## Quickstart - -1. Launch a PowerShell console (5.1 or 7+). Run as Administrator if you plan to execute privileged actions. -2. Navigate to the extracted toolkit directory. -3. Start the menu: - -```powershell -.\PSToolkit.ps1 -``` - -### Interactive Session - +1. **Clone the repository** + ```powershell + git clone https://github.com/your-org/PSToolkit.git + cd PSToolkit + ``` +2. **Review execution policy** (if not already permitting local scripts) + ```powershell + Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned + ``` +3. **Verify PowerShell version** + ```powershell + $PSVersionTable.PSVersion + ``` + +> Restore your organization’s preferred execution policy after confirming PSToolkit runs as expected. + +## Quick Start +1. Launch PowerShell with administrative rights when you intend to run maintenance tasks. +2. Navigate to the cloned repository directory. +3. Execute the script: + ```powershell + .\PSToolkit.ps1 + ``` +4. Follow the on-screen prompts to select diagnostic or maintenance actions. Logs and JSON exports are created automatically. + +### Example Session ```text -=== PSToolkit === -1) Network Diagnostics -2) System Health Check -3) Performance Snapshot -4) Maintenance Toolkit -5) Export JSON Report -Q) Quit -Select an option: 1 -``` - -### Non-Interactive Mode - -Use flags to run a single action and exit: - -```powershell -.\PSToolkit.ps1 -Action NetworkDiagnostics -ExportJson -JsonPath .\Outputs\Reports\netdiag.json -Verbose -``` - ---- - -## Usage Details - -### Menu Flow - -```mermaid -flowchart TD - Start([Launch PSToolkit]) --> Menu{Select Action} - Menu -->|1| NetDiag[Network Diagnostics] - Menu -->|2| SysHealth[System Health Check] - Menu -->|3| PerfSnap[Performance Snapshot] - Menu -->|4| Maintenance[Maintenance Toolkit] - Menu -->|5| Export[Export JSON Report] - NetDiag --> Logs[Write Logs] - SysHealth --> Logs - PerfSnap --> Logs - Maintenance --> Logs - Export --> Logs - Logs --> Menu - Menu -->|Q| Exit((Exit)) +Select a support option: +1. Network Diagnostics +2. System Diagnostics +3. Performance Monitoring +4. Maintenance Tools +5. Exit +Enter your choice (1-5): 1 ``` -### Command-Line Flags - -| Flag | Type | Default | Description | -| --- | --- | --- | --- | -| `-Action` | `string` | `""` | Optional. Specify an action key (`NetworkDiagnostics`, `SystemHealth`, `Performance`, `Maintenance`, `ExportJson`). | -| `-ExportJson` | `switch` | `False` | Toggle JSON export for the current run. | -| `-JsonPath` | `string` | `Outputs\Reports\PSToolkit.json` | Target path for JSON export. Creates folders as needed. | -| `-LogPath` | `string` | `Outputs\Logs` | Custom directory for log output. | -| `-ConfigPath` | `string` | `config.json` | Alternative configuration file. | -| `-Verbose` | `switch` | `False` | Enable verbose logging for troubleshooting. | -| `-WhatIf` | `switch` | `False` | Simulate actions without applying system changes (where supported). | - -### JSON Export Schema - -```jsonc -{ - "runId": "2023-09-21T19-04-55Z", - "host": { - "computerName": "WORKSTATION-01", - "userName": "contoso\\jdoe", - "powerShellVersion": "7.3.3" - }, - "actions": [ - { - "name": "NetworkDiagnostics", - "status": "Success", - "durationSeconds": 52, - "output": { - "ipv4": "192.168.1.25", - "gatewayReachable": true, - "dnsTests": [ - { "target": "contoso.com", "latencyMs": 31 }, - { "target": "8.8.8.8", "latencyMs": 18 } - ] - } - } - ] -} -``` - -### Log Files - -- **Default location:** `Outputs/Logs/-PSToolkit.log` -- **Rotation:** The last 20 logs are preserved. Older logs are zipped into `Outputs/Logs/archive/` with the pattern `.zip`. -- **Transcript:** A PowerShell transcript (`Outputs/Logs/-transcript.txt`) is created for each session when run interactively. - ---- +### Output Locations +- Logs: `Outputs/Logs/SupportLog_.txt` +- JSON exports: `Outputs/Json/*.json` -## Permissions & Safety - -- **Administrator required** for maintenance tasks that modify services, registry, or system files. -- **Read-only operations** (diagnostics, performance snapshots) can run as standard users. -- **EDR/AV compatibility:** PSToolkit performs signed script verification, avoids inline binaries, and logs every privileged operation to support security reviews. - ---- - -## Configuration - -If a `config.json` file is present in the root directory, PSToolkit will merge settings in the following order (higher wins): - -1. CLI flags -2. `config.local.json` (optional, machine-specific overrides) -3. `config.json` - -Example configuration: - -```json -{ - "defaultAction": "SystemHealth", - "logRetention": 20, - "maintenance": { - "cleanupTemp": true, - "spoolerReset": false - } -} -``` +## Troubleshooting and Support +| Issue | Resolution | +| --- | --- | +| Execution policy prevents script launch | Run the installation step above to set `RemoteSigned`, then retry. | +| Log files fail to write | Confirm the current user has write access to the repository directory or set PowerShell to run as Administrator. | +| Maintenance actions warn about privileges | Rerun PowerShell as Administrator; the script exits early without elevation. | +| Windows Update check warning appears | Install the optional [PSWindowsUpdate](https://www.powershellgallery.com/packages/PSWindowsUpdate) module or skip the menu item. | ---- +For additional support or to report issues, open a ticket in the repository issue tracker with log excerpts and the selected menu path. -## Logging & Troubleshooting - -- **Verbose mode:** `-Verbose` adds granular progress records and any caught exceptions. -- **Exit codes:** `0` (success), `1` (handled error), `2` (unhandled exception), `3` (privilege escalation required). -- **Common errors:** - - *Execution policy blocks script*: Run `Set-ExecutionPolicy -Scope CurrentUser RemoteSigned`. - - *Access denied to log directory*: Use `-LogPath` with a writeable location or run with elevated rights. - - *JSON export fails*: Ensure the target directory exists or supply `-JsonPath` with a valid path. - ---- +## Development Notes +- The codebase currently consists of a single script. Future refactors should consider extracting reusable logic into a PowerShell module to improve testability. +- Repository automation now includes linting guidance via GitHub Actions (see `.github/workflows/lint.yml`). +- Planned test coverage will use [Pester](https://pester.dev/). Place future tests under the `tests/` directory. +- Run static analysis locally with `Invoke-ScriptAnalyzer -Path .` after installing `PSScriptAnalyzer`. ## Testing - -PSToolkit uses [Pester](https://pester.dev/) for unit and integration coverage. - +While automated tests are not yet implemented, contributors can prepare the environment with the following commands: ```powershell -Invoke-Pester -Path .\tests -Output Detailed +Install-Module -Name PSScriptAnalyzer -Scope CurrentUser -Force +Invoke-ScriptAnalyzer -Path .\PSToolkit.ps1 ``` - -Sample test (add to `tests/PSToolkit.Tests.ps1`): - +Add Pester tests as they are developed: ```powershell -Describe "PSToolkit Action Selection" { - It "invokes Network Diagnostics action" { - $result = .\PSToolkit.ps1 -Action NetworkDiagnostics -WhatIf - $result.Status | Should -Be "Simulated" - } -} +Invoke-Pester -Path .\tests -Output Detailed ``` -> **TODO:** Expand coverage for maintenance scripts and JSON schema validation. - ---- - -## Roadmap - -1. Offline artifact collection bundle. -2. Pluggable credential vault integration (DPAPI / SecretManagement). -3. Remote session orchestration via PowerShell remoting. -4. Centralized log shipping to Azure Log Analytics. -5. Health score summary dashboard (HTML report). -6. Self-update module using GitHub Releases API. -7. Interactive transcript viewer (Out-GridView or Terminal-UI). -8. Localization support for menu labels. - ---- - -## License & Acknowledgments - -- Licensed under the [MIT License](LICENSE). -- Built on Windows PowerShell 5.1+ and PowerShell 7+. -- Inspired by field experiences from remote desktop support engineers. - ---- - -## FAQ +## Security and Compliance +- Input prompts for ping targets and defragmentation accept raw user input. Validate entries manually before confirming operations. +- Clearing temporary files and launching Disk Cleanup or defragmentation may affect end-user workloads; communicate scheduled maintenance windows. +- Recommended security tooling: PSScriptAnalyzer for linting, secret scanning via GitHub Advanced Security (if available), and Just Enough Administration (JEA) policies for production environments. -**Will this change system settings?** -: Only maintenance tasks with explicit confirmation modify system services or files. Diagnostics are read-only. +## Dependency Overview +A high-level view of repository contents is maintained in [`docs/DEPENDENCY_OVERVIEW.md`](docs/DEPENDENCY_OVERVIEW.md). Update this document when new modules, scripts, or documentation directories are added. -**Where are logs stored?** -: In `Outputs/Logs` by default, or in the folder specified by `-LogPath`. +## License +This project is licensed under the [MIT License](LICENSE). -**How do I run headless?** -: Use non-interactive mode with `-Action` and optional `-ExportJson` flags in scheduled tasks. +## Credits +Created and maintained by Daniel Madden. Contributions are welcome via pull requests that include updated documentation and lint results. diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 0000000..89c6306 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,64 @@ +# PSToolkit Roadmap + +Author: Daniel Madden + +## Current Status +PSToolkit is a prototype-stage PowerShell script that offers interactive diagnostics and remediation menus for Windows endpoints. The codebase is monolithic and lacks automated testing, packaging, or non-interactive execution modes. Documentation and automation have now been modernized to make future improvements easier without altering functional behavior. + +## Near-Term Goals (0–3 Months) +1. **Stabilize core actions** + - Add input validation and confirmation prompts for maintenance tasks that call external executables (`defrag`, `cleanmgr.exe`). + - Wrap network and maintenance actions in `try/catch` blocks to improve user-facing error messages. + - Ensure JSON exports emit structured objects rather than raw command output strings. +2. **Introduce automation guardrails** + - Implement a `param` block to support non-interactive execution aligned with documentation expectations. + - Create Pester smoke tests covering each menu path and wire them into the CI workflow. + - Publish baseline lint configuration for PSScriptAnalyzer. + +## Mid-Term Goals (3–6 Months) +1. **Modularization** + - Refactor script functions into a PowerShell module with an accompanying module manifest. + - Separate user interface prompts from action logic to enable headless execution and reuse. +2. **Configuration and Packaging** + - Implement configuration loading from `config.json`/`config.local.json` with environment overrides. + - Prepare an automated release pipeline that packages the module for the PowerShell Gallery or internal feeds. + +## Long-Term Goals (6+ Months) +1. **Security and Observability Enhancements** + - Integrate telemetry for JSON log rotation, central log shipping, and optional event forwarding. + - Adopt Just Enough Administration (JEA) or role-based execution profiles for privileged tasks. +2. **Scalability Features** + - Add remote session orchestration (PowerShell remoting) and centralized reporting dashboards. + - Provide an extensibility model for custom remediation scripts. + +## Deferred Work and Open Questions +- Determine whether maintenance operations such as defragmentation should be scoped down or moved to a separate script due to operational risk. +- Evaluate support for non-Windows environments using PowerShell 7; most commands are Windows-specific. +- Assess logging footprint on constrained endpoints and determine retention policies. + +## Dependencies and Compatibility +- Built-in Windows tools (`ipconfig`, `systeminfo`, `cleanmgr.exe`, `defrag`) remain unversioned and tied to the host OS. Document minimum OS builds when known issues are discovered. +- Optional dependency: `PSWindowsUpdate`. Version should be pinned once functionality is implemented. +- No package manifests or module metadata currently exist. Creating a `.psd1` manifest is a prerequisite for versioned releases. + +## Security and Compliance Notes +- **Static analysis:** Recommended to run `Invoke-ScriptAnalyzer -Path .` locally and integrate results into CI. No automated findings captured yet. +- **Secret scanning:** Enable repository-level secret scanning and consider adding pre-commit hooks for credential detection. +- **Risk areas:** + - User-provided input for `defrag` and `Test-Connection` is not sanitized. + - TEMP directory cleanup can remove files still in use; add warnings and exclusions. + - Windows Update check is a placeholder and should either be implemented securely or hidden until ready. +- **Simulated audits:** As part of this review, PowerShell-specific tooling such as PSScriptAnalyzer and recommended security scans were documented but not executed in the CI pipeline (output is informational only). + +## Audit Findings Summary +- Repository now includes `.gitignore`, documentation, and CI scaffolding to support future modernization. +- Tests remain absent; investment in Pester coverage is a prerequisite for higher maturity. +- Documentation now reflects actual behavior, removing references to unimplemented CLI flags. +- Non-destructive improvements were prioritized; functional code remains unchanged pending future feature work. + +## Audit Summary +- Dependencies checked and aligned with current script requirements; no external packages are bundled. +- Deprecated settings replaced per Python.org guidance for 2026: not applicable (PowerShell project). +- Security tools recommended but not executed; instructions are documented above for manual runs. +- CI workflow ready for continuous review with linting and simulated security audit steps. +- No functional changes made to the PowerShell script during this audit. diff --git a/docs/DEPENDENCY_OVERVIEW.md b/docs/DEPENDENCY_OVERVIEW.md new file mode 100644 index 0000000..ded99cc --- /dev/null +++ b/docs/DEPENDENCY_OVERVIEW.md @@ -0,0 +1,28 @@ +# PSToolkit Dependency Overview + +The project currently consists of a single interactive PowerShell script. The layout below highlights the primary assets and their responsibilities. + +``` +PSToolkit/ + ├── PSToolkit.ps1 → Interactive diagnostics and maintenance menu + ├── README.md → Project overview, usage, and contributor guidance + ├── docs/ → Extended documentation and architecture notes + │ └── DEPENDENCY_OVERVIEW.md → This document + ├── tests/ → Placeholder for future Pester-based test suites + ├── .github/workflows/ → Continuous integration definitions + │ └── lint.yml → Lint and audit workflow for GitHub Actions + ├── .gitignore → Repository hygiene rules for generated artifacts + ├── LICENSE → MIT license terms + ├── CHANGELOG.md → Versioned summary of repository-level updates + └── ROADMAP.md → Planned enhancements, audit notes, and security guidance +``` + +## Script Dependencies +- Built-in Windows executables: `ipconfig`, `systeminfo`, `cleanmgr.exe`, `defrag`. +- PowerShell cmdlets: `Get-Process`, `Get-EventLog`, `Get-CimInstance`, `Restart-Service`, `Start-Process`, and `Test-Connection`. +- Optional module: `PSWindowsUpdate` for Windows Update integration (not bundled). + +## Documentation and Automation +- Documentation artifacts live under `docs/` and the repository root. +- Continuous integration tooling is defined under `.github/workflows/` and uses GitHub-hosted runners (`ubuntu-latest`) with PowerShell 7. +- No packaged modules or external libraries are committed; repository consumers should install optional dependencies locally as needed. diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..1f5e70a --- /dev/null +++ b/tests/README.md @@ -0,0 +1,15 @@ +# Tests + +This directory is reserved for future Pester-based unit and integration tests. Contributors should: + +1. Install Pester if it is not already available: + ```powershell + Install-Module -Name Pester -Scope CurrentUser -Force + ``` +2. Add test files following the `*.Tests.ps1` naming convention. +3. Run the suite locally with: + ```powershell + Invoke-Pester -Path . -Output Detailed + ``` + +Document new test cases in `CHANGELOG.md` and update the CI workflow if additional setup steps are required.