I'm trying to figure out how to use PowerShell to extract the 7th and 13th lines from a bunch of text files in a directory. I've been looking into commands like Get-ChildItem and Get-Content, but I keep running into problems—right now, I can only get the 7th line from the first file without moving on to the others.
The files I'm working with are in UTF-16 LE format, which I know isn't compatible with CMD. I'd prefer to stick with PowerShell since it handles those files better. All the .txt files will be in one folder, and I want to write the extracted lines to a file called Out.txt. Any guidance on how to do this would be greatly appreciated!
5 Answers
You’re on the right track! Here's a simple way to achieve what you need:
```powershell
Get-ChildItem *.txt | ForEach-Object {
Get-Content $_ | Select-Object -Index 7,13
} | Set-Content Out.txt
```
This script will loop through each .txt file in the directory, grab the lines you want, and save everything into Out.txt. Just remember that the first line is indexed as 0, so line 7 is actually the 8th line in the file.
Just a heads up, if you’re looking for straightforward answers, consider if you want to learn the ins and outs of scripting or just get something that works. Both paths have their merits!
If you prefer a more customized approach, consider this:
```powershell
Get-ChildItem -Path "C:PathToTexts" -Filter *.txt | ForEach-Object {
$lines = Get-Content $_.FullName
[PSCustomObject]@{
File = $_.Name
Line7 = $lines[6]
Line13 = $lines[12]
}
}
```
This will create a custom object for each file containing the lines you're interested in. You can then output or manipulate these objects further!
Have you thought about using artificial intelligence tools for this task? They can help streamline the process, but always double-check the commands they give.
Also, if you're working with larger files, you might want to avoid `Get-Content` as it loads the entire file at once. Instead, try using a StreamReader to read lines one by one:
```powershell
$files = Get-ChildItem $yourDir -File
$results = [System.Collections.ArrayList]::new()
foreach ($file in $files) {
$reader = [System.IO.StreamReader]::new($file.FullName)
$lineNumber = 1
while (($line = $reader.ReadLine()) -ne $null) {
if ($lineNumber -eq 7 -or $lineNumber -eq 13) {
[void]$results.Add([PSCustomObject]@{
File = $file.Name
LineNumber = $lineNumber
Content = $line
})
}
$lineNumber++
}
$reader.Close()
}
$results
```
This method reads the file line by line, which can be more efficient!

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically