Introduction
Best practices help scripts work correctly every time. They make scripts easier to understand and fix if something goes wrong.
Jump into concepts and practice - no test required
# No specific syntax for best practices, but here are examples: # Use clear variable names $backupPath = "C:\Backups" # Check for errors try { Copy-Item -Path $source -Destination $backupPath -ErrorAction Stop } catch { Write-Error "Backup failed: $_" }
# Use clear variable names $logFile = "C:\Logs\script.log"
# Use error handling try { Remove-Item -Path "C:\Temp\file.txt" -ErrorAction Stop } catch { Write-Error "Could not delete file: $_" }
# Add comments to explain code # This copies files to backup folder Copy-Item -Path "C:\Data" -Destination "C:\Backup"
# PowerShell script showing best practices # Define source and backup paths $source = "C:\Data" $backupPath = "C:\Backup" # Check if backup folder exists, create if not if (-not (Test-Path -Path $backupPath)) { New-Item -ItemType Directory -Path $backupPath | Out-Null Write-Output "Created backup folder at $backupPath" } # Try to copy files and handle errors try { Copy-Item -Path "$source\*" -Destination $backupPath -Recurse -ErrorAction Stop Write-Output "Backup completed successfully." } catch { Write-Error "Backup failed: $_" }
# for single-line comments.#, which is correct. Others are from different languages.try {
Get-Item 'C:\NonExistentFile.txt'
} catch {
Write-Output 'File not found'
}if (Test-Path 'C:\file.txt') Write-Output 'File exists' Write-Output 'File OK' else Write-Output 'File does not exist'