r/PowerShell • u/Zandizar • Nov 30 '25
Need help using Powershell or CMD to extract lines lots of txt files.
I'm in need of help getting Powershell (or CMD) to extract lines 7 and 13 from hundreds of txt files in a directory. I've been looking into options such as Get-ChildItem, Get-Content, Select-String, and ForEach-Object but I can't quite get them to do what I want. I've been experimenting with several configurations but the best I can get is the 7th from the first file and no further.
These files are in UTF-16 LE, which I know CMD doesn't like. So since PS plays nicer with them, I've been using it.
I'll have all the txt files in one directory and running it from there, so no need to direct it. I just need it to take the 7th and 13th lines from each file in the dir and Out-File it to Out.txt
Any help would be much appreciated, thank you.
25
u/korewarp Nov 30 '25 edited Nov 30 '25
Show us the code you have so far.
Steps:
Another consideration is how large the files are.
Get-Contentis not very efficient.13
u/g3n3 Nov 30 '25
Are you wanting to learn or get given a script to do the work without you working at all?
4
u/narcissisadmin Nov 30 '25
I've tried nothing and I'm all out of ideas.
7
u/ka-splam Nov 30 '25 edited Nov 30 '25
[edited with u/Thotaz ' comment in mind]
20
u/mudgonzo Nov 30 '25
Holy shit, 50% of the comments here are either straight copy paste from ChatGPT or «use an llm».
Let’s just shut this subreddit down then.
4
u/Gomeology Nov 30 '25 edited Nov 30 '25
Powershell Get-content <file> | select-object -index <line number>
Keep in mind line 1 is index 0
Edit Or you can loop it in a object
Get-ChildItem -Path "C:\Path\To\Texts" -Filter *.txt | ForEach-Object { $lines = Get-Content $_.FullName [PSCustomObject]@{ File = $_.Name Line8 = $lines[7] Line13 = $lines[12] } }something like that1
u/faulkkev Nov 30 '25 edited Nov 30 '25
Lookup $myinvocation built in variable. I know there are other ways as well I have searched for patterns before and returned line number.
You might try setting get-content to a variable and try variable[7] and [13]. Not sure if that will pull a line or not.
Similar this this:
$filePath = "C:\Users\YourUser\Documents\example.txt" $fileContent = Get-Content -Path $filePath $lineNumber = 3 $specificLine = $fileContent[$lineNumber - 1] Write-Host "The 3rd line is: $specificLine"
1
u/cous_cous_cat Dec 01 '25
Why??
1
u/Quiet-Technician6499 Dec 04 '25
There is an example of this right on the Microsoft article for this cmdlet. Ten seconds of searching would have given you the answer.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-content?view=powershell-7.5#example-3-get-a-specific-line-of-content-from-a-text-file
0
u/toni_z01 Nov 30 '25
here you go
-20
u/Tymanthius Nov 30 '25
One of the AI tools can probably help you with this. But vet the command first, as always.
0
u/[deleted] Nov 30 '25
[deleted] — view deleted comment