@@ -68,7 +68,7 @@ function Invoke-DbatoolsFormatter {
68
68
' PSUseConsistentIndentation' ,
69
69
' PSUseConsistentWhitespace'
70
70
)
71
- Rules = @ {
71
+ Rules = @ {
72
72
PSPlaceOpenBrace = @ {
73
73
Enable = $true
74
74
OnSameLine = $true
@@ -115,7 +115,29 @@ function Invoke-DbatoolsFormatter {
115
115
Stop-Function - Message " Cannot find or resolve $p " - Continue
116
116
}
117
117
118
- $originalContent = Get-Content - Path $realPath - Raw - Encoding UTF8
118
+ # Skip directories and non-PowerShell files
119
+ if (Test-Path - Path $realPath - PathType Container) {
120
+ Write-Message - Level Verbose " Skipping directory: $realPath "
121
+ continue
122
+ }
123
+
124
+ if ($realPath -notmatch ' \.ps1$|\.psm1$|\.psd1$' ) {
125
+ Write-Message - Level Verbose " Skipping non-PowerShell file: $realPath "
126
+ continue
127
+ }
128
+
129
+ try {
130
+ $originalContent = Get-Content - Path $realPath - Raw - Encoding UTF8
131
+ } catch {
132
+ Stop-Function - Message " Unable to read file $realPath : $ ( $_.Exception.Message ) " - Continue
133
+ }
134
+
135
+ # If Get-Content failed, originalContent might be null or empty
136
+ if (-not $originalContent ) {
137
+ Write-Message - Level Verbose " Skipping empty or unreadable file: $realPath "
138
+ continue
139
+ }
140
+
119
141
$content = $originalContent
120
142
121
143
if ($OSEOL -eq " `r`n " ) {
@@ -134,8 +156,16 @@ function Invoke-DbatoolsFormatter {
134
156
# Use custom settings instead of CodeFormattingOTBS
135
157
$content = Invoke-Formatter - ScriptDefinition $content - Settings $customSettings - ErrorAction Stop
136
158
} catch {
137
- Write-Message - Level Warning " Unable to format $p "
159
+ Write-Message - Level Warning " Unable to format $realPath : $ ( $_.Exception.Message ) "
160
+ continue
161
+ }
162
+
163
+ # Ensure $content is a string before processing
164
+ if (-not $content -or $content -isnot [string ]) {
165
+ Write-Message - Level Warning " Formatter returned unexpected content type for $realPath "
166
+ continue
138
167
}
168
+
139
169
# match the ending indentation of CBH with the starting one, see #4373
140
170
$CBH = $CBHRex.Match ($content ).Value
141
171
if ($CBH ) {
@@ -170,8 +200,12 @@ function Invoke-DbatoolsFormatter {
170
200
171
201
# Only write the file if there are actual changes
172
202
if ($finalContent -ne $originalContent ) {
173
- Write-Message - Level Verbose " Formatting changes detected in $realPath "
174
- [System.IO.File ]::WriteAllText($realPath , $finalContent , $Utf8NoBomEncoding )
203
+ try {
204
+ Write-Message - Level Verbose " Formatting changes detected in $realPath "
205
+ [System.IO.File ]::WriteAllText($realPath , $finalContent , $Utf8NoBomEncoding )
206
+ } catch {
207
+ Stop-Function - Message " Unable to write file $realPath : $ ( $_.Exception.Message ) " - Continue
208
+ }
175
209
} else {
176
210
Write-Message - Level Verbose " No formatting changes needed for $realPath "
177
211
}
0 commit comments