locked
Output lines of text file into csv RRS feed

  • Question

  • Hi folks,

    I'm trying what should be relatively simple, but it's not working. Can someone tell me where I'm going wrong? Here's the code:

    $path = "c:\files\"
    Get-ChildItem $path -Filter *.txt | `
    ForEach-Object{
        "{0}`t{1}" -f (Get-Content $_ | Select-Object -Index 0),(Get-Content $_ | Select-Object -Index 1) | Out-File c:\files\test.csv -Append
        }

    Each txt file has 2 lines, one work on each line. I want to output each pair of lines to a single line in a CSV file (comma or tab separated.

    The error I get is:

    Get-Content : Cannot find path 'C:\Windows\system32\test.txt' because it does not exist.
    At line:4 char:62
    +     "{0}`t{1}" -f (Get-Content $_ | Select-Object -Index 0),(Get-Content $_ | Se ...
    +                                                              ~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (C:\Windows\system32\test.txt:String) [Get-Content], ItemNotFoundException
        + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand

    Why is it looking at the system path??

    Thanks,

    F.

    Sunday, May 31, 2015 10:11 AM

Answers

  • Your method will not produce a result as you cannot cascade a pipe like that.

    Try this:

    Get-ChildItem c:\files\*.txt |
        ForEach-Object{
            $f=Get-Content $_
            [pscustomobject]@{F1=$f[0];F2=$f[1]}
        } |
        Export-Csv c:\files\test.csv -NoType
    


    \_(ツ)_/

    • Proposed as answer by AnnaWY Thursday, June 4, 2015 6:14 AM
    • Marked as answer by AnnaWY Saturday, June 6, 2015 7:09 AM
    Sunday, May 31, 2015 2:26 PM

All replies

  • Try Get-Content $_.FullName. I am thinking that is is just using the Name property when passing over the pipeline, and then it is looking for that file, in the location where the console window is currently at.

    If you find that my post has answered your question, please mark it as the answer. If you find my post to be helpful in anyway, please click vote as helpful.

    Don't Retire Technet

    Sunday, May 31, 2015 12:28 PM
  • Your method will not produce a result as you cannot cascade a pipe like that.

    Try this:

    Get-ChildItem c:\files\*.txt |
        ForEach-Object{
            $f=Get-Content $_
            [pscustomobject]@{F1=$f[0];F2=$f[1]}
        } |
        Export-Csv c:\files\test.csv -NoType
    


    \_(ツ)_/

    • Proposed as answer by AnnaWY Thursday, June 4, 2015 6:14 AM
    • Marked as answer by AnnaWY Saturday, June 6, 2015 7:09 AM
    Sunday, May 31, 2015 2:26 PM
  • Excellent, thanks. So simple when you get the solution. :-)
    Monday, June 1, 2015 9:39 AM