Best Practices
This page provides guidance on writing efficient, maintainable, and performant SPE scripts for working with Sitecore items.
Performance Optimization
Query Method Selection
Choose the right query method based on your use case:
Get-Item by path
Single known item
⭐⭐⭐
✓
✓
Get-ChildItem
Small trees (<500 items)
⭐⭐
✓
✓
Sitecore Query
Specific criteria, medium trees
⭐⭐
✓
✓
Find-Item
Large trees (>500 items)
⭐⭐⭐⭐
✓
Partial
Example: Performance comparison for finding items by template.
# SLOW - Retrieves all items then filters
$items = Get-ChildItem -Path "master:\content" -Recurse |
Where-Object { $_.TemplateName -eq "Sample Item" }
# FASTER - Uses Sitecore query to filter server-side
$items = Get-Item -Path "master:" -Query "/sitecore/content//*[@@templatename='Sample Item']"
# FASTEST - Uses the search index
# See Find-ItemBulk Update Performance
When updating many items, use appropriate context objects to improve performance:
Example: Performance tiers for bulk updates.
Memory Management
For large datasets, process items in batches to avoid memory issues. Use Find-Item with pagination to retrieve items server-side rather than loading everything into memory:
Example: Efficient batch processing with search index pagination.
Caching Considerations
//TODO
Security Best Practices
//TODO
Validating Access
//TODO
Code Organization
Function Structure
Create reusable functions with proper error handling:
Example: Well-structured function.
Error Handling
Implement comprehensive error handling:
Example: Robust error handling pattern.
Progress Reporting
Always provide feedback for long-running operations:
Example: Comprehensive progress reporting.
Note: Use the Bulk Data Generator found under the Toolbox to create test items.
Language and Version Handling
Working with Multiple Languages
Be explicit about language handling:
Example: Multi-language update pattern.
Version Management
Handle versions carefully to avoid unintended consequences:
Example: Safe version operations.
Field Type Handling
Type-Safe Field Access
Use typed field access when working with complex fields:
Example: Safe field type handling.
Date Handling
Always use ISO format for date fields:
Example: Proper date handling.
Testing and Validation
Dry Run Support
Implement dry-run mode for destructive operations:
Example: Dry-run pattern.
Validation Before Operations
Validate data before making changes:
//TODO
Logging and Auditing
Comprehensive Logging
Log operations for audit trails:
Example: Logging pattern.
Common Anti-Patterns
❌ Anti-Pattern: Not Checking Item Existence
❌ Anti-Pattern: Inefficient Queries
//TODO
❌ Anti-Pattern: Swallowing Errors
Performance Benchmarking
Use Measure-Command to identify bottlenecks:
Example: Performance comparison.
See Also
Retrieving Items - Query optimization techniques
Editing Items - Update performance patterns
Item Security - Security best practices
Appendix - Common Commands - Cmdlet reference
References
Last updated