Writes text to a file, retrying if the write fails.


Write-File [-Path] <Object> [-InputObject] <String[]> [[-MaximumTries] <Int32>] [[-RetryDelayMilliseconds] <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>]


The Write-File function writes text file to a file, and will retry if the write fails. Use this function if you need to write text files that can be intermittently locked, like the Windows hosts file.

By default, it will retry 30 times, waiting 100 milliseconds between each try. You can control the number of retries and the wait between retries with the MaximumTries and RetryDelayMilliseconds parameters, respectively.

All errors raised while trying to write the file are ignored, except the error raised on the last try.

This function was introduced in Carbon 2.2.0.


Name Type Description Required? Pipeline Input Default Value
Path Object

The path to the file to read.

true false
InputObject String[]

The contents of the file

true true (ByValue)
MaximumTries Int32

The number of tries before giving up reading the file. The default is 100.

false false 30
RetryDelayMilliseconds Int32

The number of milliseconds to wait between tries. Default is 100 milliseconds.

false false 100
WhatIf SwitchParameter false false
Confirm SwitchParameter false false
CommonParameters This cmdlet supports common parameters. For more information type
Get-Help about_CommonParameters.


$lines | Write-File -Path 'C:\Path\to\my\file'

Demonstrates how to write lines to a text file using the pipeline.


Write-File -Path 'C:\Path\to\my\file' -InputObject $lines

Demonstrates how to write lines to a text file using a variable.


$lines | Write-File -Path 'C:\Path\to\my\file' -MaximumRetries 10 -RetryDelayMilliseconds 1000

Demonstrates how to control how long to retry writing the text file. In this case, Write-File will try 10 times, waiting one second between tries.


$lines | Write-File -Path 'C:\Path\to\my\file' -ErrorVariable 'writeErrors'

Demonstrates how to check if the write failed. In this case, errors are copied to a 'writeErrors' variable, so you would check if this error variable has any items.