PowerShell Write to File [With Examples]

If you are working as a PowerShell administrator, then you should know how to write to a file in PowerShell. PowerShell provides different methods for writing to files.

I will show you here how to write data to a file using PowerShell, using different methods and examples.

Method 1: Using Out-File Cmdlet

The Out-File cmdlet is used to write content to a file in PowerShell. This method redirects output from a command to a file rather than to the console.

Basic Syntax:

"Hello World" | Out-File -FilePath C:\Bijay\example.txt

Key Parameters:

  • -FilePath: Specifies the path where you want to create the file
  • -Append: Adds content to the end of an existing file instead of replacing it
  • -Encoding: Sets the type of encoding for the file (UTF8, ASCII, etc.)
  • -NoClobber: Prevents overwriting an existing file

Let us see some examples to understand this.

Example with Options:

Before showing you how to write to a file with options in PowerShell, let me show you a simple example.

The script below will add static text to the file using the Out-File cmdlet.

"This is a static text written to the file using Out-File." | Out-File -FilePath "C:\Bijay\example.txt"

Once you execute the script, it creates the text file and adds its content. See the screenshot for reference.

powershell write to file
Get-Process | Out-File -FilePath C:\temp\processes.txt -Append -Encoding UTF8

This command will append a list of running processes to the processes.txt file using UTF-8 encoding.

Check out Rename Multiple Files Using PowerShell

Method 2: Using Set-Content for Direct File Writing

The Set-Content cmdlet offers more control when writing to files using PowerShell. Unlike Out-File, which redirects output streams, Set-Content is designed specifically for writing content to files.

Basic Syntax:

Set-Content -Path C:\temp\example.txt -Value "Hello World"

Key Benefits:

  • More direct control over content
  • Better performance with large files
  • Simpler syntax for some scenarios

Example for Multiple Lines:

$content = @"
Line 1
Line 2
Line 3
"@

Set-Content -Path C:\Bijay\multiline.txt -Value $content

I executed the above PowerShell script using VS Code; you can see the exact output. Here is a screenshot for your reference.

powershell output to file

Check out Check if a File Exists and Rename it Using PowerShell

Method 3: Add-Content for Appending Data

If you want to add information to an existing file without overwriting its contents, then you can use the Add-Content cmdlet in PowerShell.

Basic Syntax:

Add-Content -Path C:\temp\log.txt -Value "New log entry at $(Get-Date)"

Practical Example – Creating a Simple Log:

Here is a practical example.

function Add-LogEntry {
    param (
        [string]$LogMessage
    )
    
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] $LogMessage"
    
    Add-Content -Path C:\Logs\application.log -Value $logEntry
}

Add-LogEntry "Application started"
# Do some work
Add-LogEntry "Operation completed successfully"

You can see the exact output in the screenshot below:

powershell out-file

Check out Download a File from URL Using PowerShell

Method 4: Using the StreamWriter Class

You can also use the .NET StreamWriter class directly from PowerShell to write to files.

Basic Example:

Here is an example to write to a file using the StreamWriter Class.

$file = "C:\temp\streamwriter-example.txt"
$streamWriter = New-Object System.IO.StreamWriter $file
$streamWriter.WriteLine("First line")
$streamWriter.WriteLine("Second line")
$streamWriter.Close()

Here are some benefits of using StreamWriter in PowerShell

  • Higher performance with large files
  • More granular control over file writing
  • Access to additional .NET capabilities

Check out Check If File Modified In Last 24 Hours Using PowerShell

Method 5: Create Files with the PowerShell New-Item Cmdlet

The New-Item cmdlet is perfect when you need to create a new file before writing to it.

Basic Syntax:

New-Item -Path C:\temp\newfile.txt -ItemType File -Value "Initial content"

Create Multiple Files:

You can also create multiple files in PowerShell using the New-Item. Here is the syntax.

1..5 | ForEach-Object {
    New-Item -Path "C:\temp\file$_.txt" -ItemType File -Value "This is file $_"
}

Read Create a File in PowerShell if it Doesn’t Exist

Comparison of PowerShell File Writing Methods

Here is a summary of all the above file writing methods in PowerShell. You can decide which method to use and when.

MethodProsConsBest For
Out-FileSimple to use, Works with pipelineSlower with large filesQuick scripts, Console redirection
Set-ContentDirect and intuitive, Better performance than Out-FileLess pipeline-friendlyDirect file writing, replacing content
Add-ContentPerfect for logs, Simple appendingCan be slow with very large filesLogs, Incremental data collection
StreamWriterHighest performance, Most controlMore complex syntaxLarge files, Performance-critical operations
New-ItemCreates files and folders, Can set initial contentLess specialized for content writingCreating files with initial content

Read Create a Log File using PowerShell

PowerShell Write to File Examples

I will show you some real examples of writing to a file in PowerShell.

Create Configuration Files

Now, let me show you how to create configuration files using PowerShell.

$config = @{
    Environment = "Production"
    Database = "SQL01"
    MaxConnections = 100
    Debug = $false
}

$config | ConvertTo-Json | Out-File -FilePath C:\App\config.json

Export Reports

Here is another example of writing to a file using PowerShell.

# Get all services and export to CSV
Get-Service | Export-Csv -Path C:\Reports\services.csv -NoTypeInformation

# Export specific services to HTML
Get-Service | Where-Object {$_.Status -eq "Running"} | 
    ConvertTo-Html -Property Name,DisplayName,Status | 
    Out-File C:\Reports\running-services.html

Log Rotation Example

Here’s a more complex example that demonstrates log rotation – a common administrative task:

function Rotate-Log {
    param(
        [string]$LogPath = "C:\Logs\application.log",
        [int]$MaxSizeMB = 10,
        [int]$KeepLogs = 5
    )
    
    # Check if log exists and exceeds size limit
    if (Test-Path $LogPath) {
        $logFile = Get-Item $LogPath
        if (($logFile.Length / 1MB) -gt $MaxSizeMB) {
            # Rotate existing backup logs
            for ($i = $KeepLogs; $i -gt 1; $i--) {
                $oldLog = "$LogPath.$($i-1)"
                $newLog = "$LogPath.$i"
                
                if (Test-Path $oldLog) {
                    Move-Item -Path $oldLog -Destination $newLog -Force
                }
            }
            
            # Move current log to .1
            Move-Item -Path $LogPath -Destination "$LogPath.1" -Force
            
            # Create new empty log
            New-Item -Path $LogPath -ItemType File | Out-Null
            
            return $true
        }
    } else {
        # Create log if it doesn't exist
        New-Item -Path $LogPath -ItemType File -Force | Out-Null
    }
    
    return $false
}

Read PowerShell Copy-Item Cmdlet to Copy Files and Folders

Best Practices For Writing to a File in PowerShell

Now, let me show you some best practices for writing to a file using PowerShell.

  1. Always check if a file exists before trying to write to it; here is an example.
if (Test-Path $filePath) {
    # File exists, decide whether to append or overwrite
} else {
    # Create new file
}
  1. Use try/catch blocks for error handling:
try {
    "Content" | Out-File -FilePath $filePath -ErrorAction Stop
    Write-Host "File written successfully"
} catch {
    Write-Error "Failed to write file: $_"
}

Conclusion

PowerShell provides multiple ways to write to files. For simple scenarios, Out-File and Set-Content are perfect, while more complex requirements might call for StreamWriter or a combination of approaches.

In this tutorial, I explained everything about “PowerShell write to files“.

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App