2

I have a well-formed CSV file that I want to read, reformatting some values while doing so. For some reason the code below does not work ($csv variable ends up being empty):

$csv = Import-Csv "result.log" -Delimiter "|" | ForEach-Object {
    $_.PSObject.Properties.Value | ForEach-Object {
        if ($_ -like '*---*') { $_ = "" }
    }
}

What am I doing wrong?

1
  • You need to output the current object at the end of the outer ForEach-Object loop: $csv = Import-Csv ... | ForEach-Object { ...; $_ }. Otherwise there won't be any output to capture in $csv. Commented Jul 10, 2017 at 10:04

1 Answer 1

1

Your result is blank because you aren't returning anything to the pipeline (you are just changing the value of one or more properties but then not outputting them).

There might be a simpler solution but I think this achieves what you want:

$CSV = Import-Csv "result.log" -Delimiter "|" | Foreach-Object {
    $Output = New-Object -TypeName PSObject

    $_.PSObject.Properties | Foreach-Object {
        If ($_.Value -like '*---*') { $_.Value = '' }
        $Output | Add-Member -Name $_.Name -Value $_.Value -MemberType NoteProperty   
    }

    $Output
}

This performs the following for each row of the CSV:

  • creates a new empty PowerShell object
  • loops through the properties of the CSV, blanking ones that include --- and then uses Add-Member to add those properties to our object
  • outputs the new object to the standard pipeline

The result of this goes to the $CSV variable which you then could output as CSV via Export-CSV (or you could skip putting it in the variable and use Export-CSV on the end of the outer ForEach-Object).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.