Foreach-Object make mutable copy of $_ in PowerShell

411 Views Asked by At

I want to convert entries from Windows Event log to JSON. But I want to preformat some fields. Using ForEach-Object looks like natural decicion for me, but when I try to change attributes there like this:

Get-EventLog System -Newest 2 | % { $_.EntryType = "$($_.EntryType)" } | ConvertTo-Json

it gives me error:

'EntryType' is a ReadOnly property.

How do I made a writable copy of $_ object, or preformat objects before converting to JSON?

1

There are 1 best solutions below

0
On BEST ANSWER

You should be able to use Select-Object to do what you want. Select-Object will create entirely new objects (of type PSCustomObject) that you can customize. You can also limit the properties that you actually want, and you can define your own calculated properties.

See this article for more information about calculated properties.

Get-EventLog System -Newest 2 |
    Select-Object Index, Time, Source, InstanceID, @{Name='MyEntryType';Expression={$_.EntryType } } |
    ConvertTo-Json