Tony
Tony

Reputation: 9571

Powershell get all errors not just first

I have a command like so:

(($remoteFiles | Where-Object { -not ($_ | Select-String -Quiet -NotMatch -Pattern '^[a-f0-9]{32}(  )') }) -replace '^[a-f0-9]{32}(  )', '$0=  ' -join "`n") | ConvertFrom-StringData

sometimes it throws a

ConvertFrom-StringData : Data item 'a3512c98c9e159c021ebbb76b238707e' in line 'a3512c98c9e159c021ebbb76b238707e  =  My Pictures/Tony/Automatic Upload/Tony’s iPhone/2022-10-08 21-46-21 (2).mov' 
is already defined.

BUT I believe there to be more and the error is only thrown on the FIRST occurrence, is there a way to get all of the errors so I can act upon them?

Upvotes: 1

Views: 36

Answers (1)

mklement0
mklement0

Reputation: 437176

is there a way to get all of the errors

I'm afraid there is not, because what ConvertFrom-StringData reports on encountering a problem is a statement-terminating error, which means that it aborts its execution instantly, without considering further input.


You'd have to perform your own analysis of the input in order to detect multiple problems, such as duplicate keys; e.g.:

@'
a = 1
b = 2
a = 10
c = 3
b = 20
'@ | ForEach-Object {
  $_ -split '\r?\n' |
    Group-Object { ($_ -split '=')[0].Trim() } |
    Where-Object Count -gt 1 |
    ForEach-Object {
      Write-Error "Duplicate key: $($_.Name)"
    }
}

Output:

Write-Error: Duplicate key: a
Write-Error: Duplicate key: b

Upvotes: 2

Related Questions