Piping issue in windows powershell

t jk 21 Reputation points
2022-02-02T03:26:08.8+00:00

Hello and happy new year!

I want to use Windows PowerShell to merge some .txt files into an INP file for Abaqus.
Examples.
$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 for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 47,901 Reputation points
    2022-02-03T03:23:11.253+00:00

    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 123.6K Reputation points MVP Volunteer Moderator
    2022-02-02T20:32:38.967+00:00

    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)

    Regards
    Andreas Baumgarten


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.