Piping issue in windows powershell

t jk 21 Reputation points

Hello and happy new year!

I want to use Windows PowerShell to merge some .txt files into an INP file for Abaqus.
$Sname = “Sample_1.inp"
New-Item $Sname
$p1 = "LP1.txt"
$p2 = "LP2_Sample_1.txt"
$p3 = "LP3.txt"
$p4 = "LP4_Sample_1.txt"
$p5 = "LP5.txt"

Merge Files

cat $p1,$p2,$p3,$p4,$p5 | Out-File -Append $Sname

When I merge files using the
cat $p1,$p2,$p3,$p4,$p5 | Out-File -Append $Sname
Or cat $p1,$p2,$p3,$p4,$p5 > $Sname
commands, the Abaqus application prompts an error. However, if I create new blank .txt files and manually paste the contents of those files into a blank document, the Abaqus application works perfectly fine.

Does Powershell's Cat command insert invisible characters when merging .txt files? Is there a better solution to merge .txt files?
I have seen some people said using "|" or ">" operations will induce character encoding problems, is there a way to avoid such problems in powershell script?

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
4,736 questions
No comments
{count} votes

Accepted answer
  1. Rich Matheisen 36,241 Reputation points

    Why are you using "-Append" as a parameter on the Out-File cmdlet? If you're just copying the contents of those five files into one file it's unnecessary.

    If you use the "-Append" you're adding the content of those five files to whatever is in the target file.

    Your uses of the ">" isn't the same as "-Append". If you want the equivalent, use ">>".

    As for the encoding, you have control of that. Just add "-Encoding X" to the "Out-File". If you want ASCII then use that in place of the "X". If you want Unicode, use that. UTF8, OEM, etc. are there for you to use as necessary.

    The -Encoding parameter is also available with the Get-Content cmd. Perhaps that's where the problem lies?

1 additional answer

Sort by: Most helpful
  1. Andreas Baumgarten 67,616 Reputation points MVP

    Hi @t jk ,

    does this work for you?

    # first option  
    $files = "C:\Junk\3\0.txt", "C:\Junk\3\1.txt", "C:\Junk\3\2.txt"  
    $Sname = "C:\Junk\3\sample_1.inp"  
    $files | ForEach-Object {  
      Get-Content $_ | Out-File -FilePath $Sname -Append  
    # second option  
    $files = "C:\Junk\3\0.txt", "C:\Junk\3\1.txt", "C:\Junk\3\2.txt"  
    $Sname = "C:\Junk\3\sample_2.inp"  
    Get-Content -Path $files | Out-File -FilePath $Sname -Append  


    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Andreas Baumgarten