Key Facts
- Error handling prevents scripts from silently failing on critical operations
- Parameter validation catches bad input before code execution
- Logging creates audit trails for compliance and debugging
- Security best practices prevent credential exposure and privilege escalation
Error Handling with Try-Catch
Always handle errors gracefully in production scripts:
try {
$service = Stop-Service -Name "BITS" -PassThru -ErrorAction Stop
Write-Host "Service stopped successfully" -ForegroundColor Green
}
catch {
Write-Error "Failed to stop service: $_"
exit 1
}
Logging Best Practices
Maintain detailed logs for auditing and troubleshooting:
function Write-Log {
param([string]$Message, [string]$Level = "INFO")
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
"$timestamp [$Level] $Message" | Add-Content "C:\Logs\automation.log"
}
# Usage
Write-Log "Starting user provisioning script"
Write-Log "Error: Cannot connect to domain" -Level "ERROR"
Write-Log "User creation completed successfully" -Level "SUCCESS"
Security: Never Hardcode Credentials
Store passwords securely, never in scripts:
# WRONG - Never do this
$password = "MyPassword123"
# RIGHT - Use Windows Credential Manager or Azure Key Vault
$credential = Get-Credential
$securePassword = Read-Host -AsSecureString "Enter password"
$credential = New-Object System.Management.Automation.PSCredential("user", $securePassword)
Key Takeaways
- Use Try-Catch-Finally for error handling in production
- Implement comprehensive logging for all automated tasks
- Never hardcode credentials in scripts
- Use -WhatIf parameter to preview changes before execution
- Version control scripts with Git for collaboration and rollback