Description
Summary
PSUseConsistentIndentation rewrites the whitespace before each comment's #, aligning every comment line in a block to the block indentation. When a run of comments is commented-out code (where the nested structure is expressed by the indentation before #), the rule flattens it, so the structure is lost. Whitespace after the # is preserved, so the two styles behave differently:
# preserved - the extra indentation is after the '#'
# if ($b) {
# doThing
# }
# flattened - the extra indentation is before the '#'
# if ($b) {
# doThing
# }Steps to reproduce
Only the one rule is enabled:
$settings = @{
IncludeRules = @('PSUseConsistentIndentation')
Rules = @{
PSUseConsistentIndentation = @{ Enable = $true; IndentationSize = 4; PipelineIndentation = 'NoIndentation'; Kind = 'tab' }
}
}Input:
if ($a) {
# if ($b) {
# doThing
# }
}Actual (Invoke-Formatter -ScriptDefinition $code -Settings $settings):
if ($a) {
# if ($b) {
# doThing
# }
}Expected: the commented-out block keeps its relative indentation (at most the whole comment run may be shifted to the code indentation).
The same happens with Kind = 'space' and when there is real code after the comment run.
Environment
- PSScriptAnalyzer 1.25.0
- PowerShell 7.6.6 on Windows
Why it matters
Commenting out a block is a common way to keep code around; flattening the indentation makes the commented-out block unreadable. Tooling that encodes directives as comments (e.g. sources that are uncommented by an external preprocessor) also relies on the indentation before # being preserved.
Related: #2151 asks for an ignore-range directive, but this is about the default behaviour of the indentation rule on ordinary comment runs.
Activity
steve02081504 commentedon Sep 18, 2026
For reference: this is the upstream behaviour behind the
restoreMarkerIndentationworkaround in the ps12exe formatter (src/.subrepo/vscode-plug/ps12exe/lib/preprocessor.mjsin https://github.com/steve02081504/ps12exe). Sources that encode conditional-compilation escapes as comments keep the code in the indentation before#, andPSUseConsistentIndentationflattened it.The workaround restores the relative indentation of those directive lines from the pre-format document. Once this is fixed upstream, delete
restoreMarkerIndentation, its export, therestores the nesting of #_!! and #_balus lines from the originalandpreserves the nesting of #_!! escapes inside a blocktests, and the corresponding AGENTS.md row.