PowerShell Concate All Text Files To One

2023-03-25

筆記如何使用 PowerShell 將多份 text file (txt 檔) 合為一份。

logo

說明

Get-ChildItem *.txt | 
  Foreach-Object {Get-Content $_ -Encoding UTF8} | 
  Set-Content all2.txt -Encoding UTF8

Conversation

Get-ChildItem

Hey, have you worked with PowerShell before?

Yes, I have used it a bit.

Great! One of the most useful cmdlets in PowerShell is Get-ChildItem. It's used to list the items in a specified location, like a directory or a folder.

Oh, I see. So it's like the ls or dir command in Linux or Windows command prompt?

Yes, exactly! In fact, Get-ChildItem is equivalent to the dir command in Windows command prompt. It displays the contents of the current directory by default, but you can specify a path to display the contents of a specific directory.

Can you give me an example of how to use it?

Sure. Let's say you want to list all the files in a directory. You would use the command Get-ChildItem C:\Users\MyUsername\Documents (assuming that's the path to your Documents folder).

Got it. And what if I want to see only the files with a certain extension?

You can use the -Filter parameter to specify a filter. For example, Get-ChildItem C:\Users\MyUsername\Documents -Filter *.txt will list only the text files in the Documents folder.

That's really helpful. Thanks for explaining it to me!

Get-Content

HHey , have you worked with PowerShell before?

Yes, a little bit.

HGreat! One of the most useful cmdlets in PowerShell is Get-Content. It's used to read the contents of a file and display them on the screen.

Oh, I see. So it's like the cat command in Linux or the type command in Windows command prompt?

HYes, exactly! In fact, Get-Content is equivalent to the type command in Windows command prompt. It allows you to view the contents of a file without having to open it in an editor.

Can you give me an example of how to use it?

HSure. Let's say you want to view the contents of a text file named "example.txt". You would use the command Get-Content C:\Users\MyUsername\Documents\example.txt (assuming that's the path to the file).

Got it. And what if I want to only see a certain number of lines from the file?

HYou can use the -TotalCount parameter to specify the number of lines to display. For example, Get-Content C:\Users\MyUsername\Documents\example.txt -TotalCount 10 will display the first 10 lines of the file.

That's really helpful. Thanks for explaining it to me, A!