Recently, I was working on a PowerShell script that needed to log information to a text file as it processed data. I needed each piece of information on a separate line, which led me to explore different methods to write to files line by line in PowerShell.
Whether you’re creating log files, exporting data, or generating reports, knowing how to write to files in PowerShell efficiently is essential. In this article, I’ll cover five different methods you can use to write to files line by line in PowerShell, along with their pros and cons. Let’s dive in!
Method 1 – Using Out-File Cmdlet
The Out-File cmdlet is one of the simplest ways to write content to a file in PowerShell. Here’s how you can use it to write line by line:
# Create a new file and write a single line
"First line of text" | Out-File -FilePath C:\Bijay\myfile.txt
# Append additional lines to the existing file
"Second line of text" | Out-File -FilePath C:\Bijay\myfile.txt -Append
"Third line of text" | Out-File -FilePath C:\Bijay\myfile.txt -Append
The -Append parameter is crucial here as it ensures that each new line is added to the end of the file rather than overwriting the existing content.
You can see the exact output in the screenshot below after I executed the above PowerShell script.

When working with loops, you can use Out-File like this:
$items = @("Item 1", "Item 2", "Item 3")
foreach ($item in $items) {
$item | Out-File -FilePath C:\Bijay\myfile.txt -Append
}
Pros and Cons of Out-File
Here are some pros and cons of the PowerShell Out-File command.
Pros:
- Simple and easy to use
- Native PowerShell cmdlet
- Supports Unicode by default
Cons:
- Can be slower for large files or frequent operations
- Opens and closes the file for each write operation in loops
Check out Append Text to Files in PowerShell
Method 2 – Using the Add-Content Cmdlet
Add-Content is another PowerShell cmdlet that’s specifically designed for appending content to files.
Here is an example.
# Create a file with initial content
Add-Content -Path C:\Bijay\myfile.txt -Value "First line of text"
# Append more lines
Add-Content -Path C:\Bijay\myfile.txt -Value "Second line of text"
Add-Content -Path C:\Bijay\myfile.txt -Value "Third line of text"
For multiple lines at once, you can use an array:
$lines = @(
"Line 1"
"Line 2"
"Line 3"
)
Add-Content -Path C:\Bijay\myfile.txt -Value $lines
Here is the output in the screenshot below; it created txt file and adding the text.

Pros and Cons of Add-Content
Here are the pros and cons of the PowerShell Add-Content cmdlet.
Pros:
- Intuitive for appending content
- Can add multiple lines at once
- Works well with pipeline input
Cons:
- Not as efficient for high-frequency write operations
- File is opened and closed with each operation
Check out PowerShell Write to File
Method 3 – Using .NET StreamWriter Class
For better performance, especially when writing many lines, the .NET StreamWriter class is an excellent choice.
Let me give you an example.
# Create a StreamWriter object
$streamWriter = New-Object System.IO.StreamWriter -ArgumentList ([string]"C:\Bijay\myfile.txt", $true)
# Write multiple lines
$streamWriter.WriteLine("First line of text")
$streamWriter.WriteLine("Second line of text")
$streamWriter.WriteLine("Third line of text")
# Close the StreamWriter when done (important!)
$streamWriter.Close()
When working with loops, the StreamWriter really shines:
$items = 1..1000
$streamWriter = New-Object System.IO.StreamWriter -ArgumentList ([string]"C:\Bijay\myfile.txt", $true)
foreach ($item in $items) {
$streamWriter.WriteLine("Item number $item")
}
$streamWriter.Close()
Don’t forget that you can also use the using statement to automatically dispose of the StreamWriter:
$filePath = "C:\Bijay\myfile.txt"
$append = $true
Using ($streamWriter = [System.IO.StreamWriter]::new($filePath, $append)) {
$streamWriter.WriteLine("Line 1")
$streamWriter.WriteLine("Line 2")
$streamWriter.WriteLine("Line 3")
}
Pros and Cons of StreamWriter
Here are the pros and cons of StreamWriter:
Pros:
- Much more efficient for multiple writes
- File stays open during multiple operations
- Better performance for large files or many lines
Cons:
- More complex syntax
- Requires explicit closing/disposing
- Need to manage the file handle manually
Check out Reference Variables in PowerShell
Method 4 – Using Set-Content with a Loop
The Set-Content cmdlet in PowerShell can create a file, and combined with a loop, you can build the content line by line:
# First, create an empty file
Set-Content -Path C:\Bijay\myfile.txt -Value $null
# Then append content in a loop
$lines = @("Line 1", "Line 2", "Line 3")
foreach ($line in $lines) {
Add-Content -Path C:\Bijay\myfile.txt -Value $line
}
Alternatively, you can build your content in memory and write it all at once:
$content = @()
$items = 1..10
foreach ($item in $items) {
$content += "This is item number $item"
}
Set-Content -Path C:\Bijay\myfile.txt -Value $content
Pros and Cons of Set-Content with Loop
Pros:
- Familiar PowerShell syntax
- Good for situations with pre-processing
Cons:
- Inefficient for line-by-line writing (opens/closes file each time)
- Building large arrays in memory can consume resources
Read Check if a File Exists and Rename it Using PowerShell
Method 5 – Using Here-Strings for Multiline Content
For predefined multiline content, PowerShell’s here-strings make it easy to write organized content:
$content = @"
First line of my file
Second line with $(Get-Date)
Third line with some $variable content
Fourth line with more text
"@
$content | Out-File -FilePath C:\Bijay\myfile.txt
You can also combine this with other methods for complex scenarios:
$header = @"
Log File
Generated on: $(Get-Date)
---------------------------
"@
$header | Out-File -FilePath C:\Bijay\logfile.txt
# Then append additional content
$items = Get-Process | Select-Object -First 5
foreach ($item in $items) {
"Process: $($item.Name), ID: $($item.Id)" | Out-File -FilePath C:\Bijay\logfile.txt -Append
}
You can see the exact output in the screenshot below after I executed the above PowerShell script.

Pros and Cons of Here-Strings
Pros:
- Very readable for predefined content
- Preserves formatting and whitespace
- Supports variable expansion
Cons:
- Not suitable for dynamic line-by-line writing
- Less efficient for content that needs to be generated iteratively
Check out Create a Log File using PowerShell
Performance Considerations
If you’re writing thousands of lines or performing frequent write operations, performance becomes important. Here’s a simple benchmark comparing three methods and you should know before using any of the above methods:
$filePath = "C:\Bijay\perftest.txt"
$iterations = 10000
# Test 1: Out-File
$sw = [System.Diagnostics.Stopwatch]::StartNew()
for ($i = 1; $i -le $iterations; $i++) {
"Line $i" | Out-File -FilePath "$filePath-1.txt" -Append
}
$sw.Stop()
"Out-File: $($sw.ElapsedMilliseconds) ms"
# Test 2: Add-Content
$sw = [System.Diagnostics.Stopwatch]::StartNew()
for ($i = 1; $i -le $iterations; $i++) {
Add-Content -Path "$filePath-2.txt" -Value "Line $i"
}
$sw.Stop()
"Add-Content: $($sw.ElapsedMilliseconds) ms"
# Test 3: StreamWriter
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$streamWriter = [System.IO.StreamWriter]::new("$filePath-3.txt", $true)
for ($i = 1; $i -le $iterations; $i++) {
$streamWriter.WriteLine("Line $i")
}
$streamWriter.Close()
$sw.Stop()
"StreamWriter: $($sw.ElapsedMilliseconds) ms"
In my testing, StreamWriter is consistently 10-20 times faster than the other methods for large numbers of write operations.
Read Get the Last Modified Date of a File in PowerShell
Real-World Example: Create a Log Function
Here’s a practical logging function I use in my scripts that writes to a file line by line:
function Write-Log {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]$Message,
[Parameter(Mandatory = $true)]
[string]$LogFilePath,
[ValidateSet('INFO', 'WARNING', 'ERROR')]
[string]$Level = 'INFO'
)
begin {
# Create the log file if it doesn't exist
if (-not (Test-Path -Path $LogFilePath)) {
New-Item -Path $LogFilePath -ItemType File -Force | Out-Null
}
}
process {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logLine = "[$timestamp] [$Level] $Message"
Add-Content -Path $LogFilePath -Value $logLine
# Also write to console with color based on level
switch ($Level) {
'INFO' { Write-Host $logLine -ForegroundColor White }
'WARNING' { Write-Host $logLine -ForegroundColor Yellow }
'ERROR' { Write-Host $logLine -ForegroundColor Red }
}
}
}
# Example usage:
# Write-Log -Message "Starting process" -LogFilePath "C:\Bijay\process.log"
# Write-Log -Message "Warning: File not found" -LogFilePath "C:\Bijay\process.log" -Level WARNING
# Write-Log -Message "Error: Operation failed" -LogFilePath "C:\Bijay\process.log" -Level ERROR
Conclusion
Writing to files line by line in PowerShell offers multiple approaches, each with its own advantages. For simple, occasional writes, Out-File or Add-Content are perfectly fine. For high-performance scenarios or when writing thousands of lines, StreamWriter is the way to go. The right method depends on your specific requirements, including performance needs, file encoding considerations, and script complexity.
I hope you found this article helpful. If you have any questions or suggestions about writing to files in PowerShell, please leave them in the comments below!
You may also like:
- Replace String in XML File using PowerShell
- Replace a String in Text File with PowerShell
- Check If a Date Is Older Than 30 Days in PowerShell

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.