Files
PowerShell-scripts/CLAUDE.md
Martien de Kleijn 62134801aa Add 12 AI-generated PowerShell scripts with documentation
⚠️ IMPORTANT: These scripts are AI-GENERATED and UNTESTED

Exchange Scripts (5):
- Get-MailboxPermissions.ps1: Audit delegate access permissions
- Get-InactiveMailboxes.ps1: Identify stale mailboxes
- Compare-MailboxDatabases.ps1: Database health comparison
- Export-DistributionGroups.ps1: Distribution group inventory
- Get-MailflowStats.ps1: Transport log analysis

Active Directory Scripts (3):
- Get-ADUserLastLogon.ps1: True LastLogon across all DCs
- Export-OUStructure.ps1: OU hierarchy with GPO links
- Compare-ADGroupMemberships.ps1: Compare user group memberships

System Maintenance Scripts (4):
- Get-ServerInventory.ps1: Hardware/software inventory report
- Monitor-DiskSpace.ps1: Disk space monitoring with alerts
- Backup-ExchangeCertificates.ps1: Certificate backup to PFX
- Test-ExchangeHealth.ps1: Aggregated Exchange health checks

Documentation:
- Updated CLAUDE.md with AI-generated scripts section
- Added AI-GENERATED-SCRIPTS.md with warnings and testing guide

All scripts include prominent warnings and follow established patterns
from existing scripts. Require thorough testing before production use.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-10-15 10:52:44 +02:00

7.3 KiB

CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

Repository Overview

This is a collection of standalone PowerShell scripts for Windows Server administration, focused on Active Directory, Exchange Server (on-premises), and system maintenance tasks. Each script is self-contained and can be executed independently.

Project Structure

The repository is organized into three main directories:

  • ActiveDirectory/ - Scripts for Active Directory management (group membership operations)
  • Exchange/ - Scripts for Exchange Server administration (mailbox reporting, inventory, traffic analysis)
  • Misc/ - System maintenance scripts (VSS backup recovery)

Script Architecture

Exchange Scripts

Exchange-Inventory.ps1 - The most complex script in this repository. Key architecture:

  • Report Generation Engine: Dual-mode output system (Word COM automation with HTML fallback)

    • Word automation via COM (Word.Application) for professional reports
    • HTML fallback with StringBuilder when Word is unavailable
    • Abstraction layer: Add-Heading(), Add-Paragraph(), Add-Table() functions work for both modes
  • Progress Tracking System: Multi-level progress reporting

    • Section-based progress ($sections array with 22 named sections)
    • Throttled progress updates ($ProgressThrottleMs parameter controls update frequency)
    • Prevents UI flooding during intensive loops (mailbox statistics, database copies)
  • Data Collection Pipeline: Sequential inventory collection

    1. Organization config & servers
    2. Client access & virtual directories (OWA, ECP, EWS, MAPI, etc.)
    3. POP/IMAP settings
    4. Certificates (with expiry status calculation)
    5. Domains, policies, transport rules
    6. Databases, DAG configuration, database copies
    7. Mailbox enumeration (on-prem only, filters out Remote* types)
    8. Mailbox statistics (collected per-database to avoid prompts)
    9. Retention, compliance, mobile device policies
    10. Addressing (address lists, GAL, OAB)
    11. Public folders, throttling, hybrid/federation config
    12. Queue monitoring
  • Storage Calculation: Computes actual mailbox space requirements

    • Parses TotalItemSize from mailbox statistics (handles KB/MB/GB/TB units)
    • Aggregates per-database and total storage (excludes whitespace)
    • Uses ToBytes() method when available, regex fallback for string parsing
  • CSV Export: Optional detailed exports controlled by $IncludeCSVs parameter

Get-LargeMailboxes.ps1 - Simple filtering script

  • Queries mailboxes > 100GB
  • Uses pipeline: Get-Mailbox | Get-MailboxStatistics | Where-Object
  • Converts bytes to GB with formatting

Get-MailboxesPerType.ps1 - Quick mailbox type inventory

  • Single-liner using Group-Object for counting

Get-SMTPTraffic.ps1 - Log parsing utility

  • Reads Exchange FrontEnd SMTP receive logs
  • CSV parsing with quoted field handling (regex: split(',(?=(?:[^"]*"[^"]*")*[^"]*$)'))
  • Filters by IP range (192.168.1.*)

System Maintenance Scripts

Fix-VSSBackup.ps1 - VSS recovery automation

  • Event log analysis (Application/System logs for VSS/VolSnap errors)
  • VSS writer status parsing via vssadmin list writers
  • Service restart orchestration with dependency handling
  • Configurable service list (VSS, SwPrv, EventSystem, SQLWriter, IISADMIN, vmicvss, etc.)
  • Smart defaults when run without parameters (auto-creates C:\Temp, enables Force mode)
  • State verification after service restart

Active Directory Scripts

CopyADgroups.ps1 - Group membership cloning

  • Simple member enumeration and addition
  • Duplicate checking before adding
  • Error handling per-member

Common Patterns

Error Handling

Scripts use -ErrorAction SilentlyContinue extensively to gracefully handle missing cmdlets or unavailable features across different Exchange versions (2013/2016/2019).

Execution Environment

  • Exchange scripts: Require Exchange Management Shell with appropriate RBAC permissions
  • VSS script: Requires Administrator privileges
  • AD scripts: Require Active Directory PowerShell module

Parameter Design

  • CmdletBinding with typed parameters
  • Configurable defaults (e.g., $TopMailboxCount = 30, $LookbackMinutes = 60)
  • Boolean parameters for feature toggles ($IncludeCSVs, $RequireFailedWriter)

Localization

Some scripts contain Dutch language strings (comments, log messages) - Exchange-Inventory.ps1 and Fix-VSSBackup.ps1 use Dutch for output.

Testing Approach

These are operational scripts without formal test frameworks. When modifying:

  1. Exchange scripts: Test in non-production Exchange Management Shell first
  2. VSS script: Test service restart logic on non-critical systems
  3. AD scripts: Use test groups before production deployment

AI-Generated Scripts (UNTESTED)

The following scripts were generated by Claude AI in 2025 and have NOT been tested in production environments. They should be thoroughly reviewed and tested in non-production environments before use:

Exchange Scripts (AI-Generated)

  • Get-MailboxPermissions.ps1 - Audits SendAs, SendOnBehalf, and FullAccess permissions
  • Get-InactiveMailboxes.ps1 - Identifies stale mailboxes based on LastLogonTime threshold
  • Compare-MailboxDatabases.ps1 - Database health comparison with alerting (whitespace, backup age)
  • Export-DistributionGroups.ps1 - Complete distribution group inventory with members
  • Get-MailflowStats.ps1 - Transport log analysis for message flow patterns and anomalies

Active Directory Scripts (AI-Generated)

  • Get-ADUserLastLogon.ps1 - True LastLogon query across all DCs (non-replicated attribute)
  • Export-OUStructure.ps1 - OU hierarchy documentation with GPO links
  • Compare-ADGroupMemberships.ps1 - Group membership comparison between two users

System Maintenance Scripts (AI-Generated)

  • Get-ServerInventory.ps1 - Comprehensive hardware/software inventory with Word/HTML report
  • Monitor-DiskSpace.ps1 - Disk space monitoring with alerting and optional email
  • Backup-ExchangeCertificates.ps1 - Certificate export to PFX with expiry warnings
  • Test-ExchangeHealth.ps1 - Aggregated Exchange health checks (services, replication, MAPI, databases)

AI-Generated Script Patterns

These scripts follow the established patterns from the original scripts:

  • Similar report generation (Word COM with HTML fallback where applicable)
  • Progress tracking for long-running operations
  • CSV export capabilities
  • -ErrorAction SilentlyContinue for graceful degradation
  • Comprehensive parameter documentation and examples
  • Prominent "⚠️ AI-GENERATED SCRIPT - UNTESTED" warnings in output

Testing Requirements: All AI-generated scripts include detailed .NOTES sections with testing guidance. Pay special attention to:

  • Permission requirements (RBAC, AD rights, Administrator)
  • Performance impact (LastLogon queries across DCs, log parsing)
  • Environment-specific assumptions (paths, IP ranges, thresholds)

Important Constraints

  • Scripts are environment-specific (hardcoded paths like C:\Program Files\Microsoft\Exchange Server\V15\...)
  • Exchange-Inventory.ps1 assumes specific Exchange cmdlet availability
  • Get-SMTPTraffic.ps1 filters for specific IP range (192.168.1.*) - modify for different networks
  • AI-generated scripts have NOT been validated in production and require thorough testing