Read-File

Reads the contents of a text file, retrying if the read fails.

Syntax

Read-File [-Path] <Object> [[-MaximumTries] <Int32>] [[-RetryDelayMilliseconds] <Int32>] [-Raw] [<CommonParameters>]

Description

The Read-File function reads the contents of a text file, and will retry if the read fails. Use this function if you need to read files that can be intermittently locked, like the Windows hosts file. The file is returned line-by-line. Use the Raw switch to return the entrie file as a single string.

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.

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

This function was introduced in Carbon 2.2.0.

Parameters

Name Type Description Required? Pipeline Input Default Value
Path Object

The path to the file to read.

true false
MaximumTries Int32

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

false false 30
RetryDelayMilliseconds Int32

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

false false 100
Raw SwitchParameter

Return the file as one string. Otherwise, by default, the file is returned line-by-line.

false false False

Return Values

System.String.

EXAMPLE 1

Read-File -Path 'C:\Path\to\my\file'

Demonstrates how to read each line from a text file.

EXAMPLE 2

Read-File -Path 'C:\Path\to\my\file' -Raw

Demonstrates how to read the entire contents of a text file into a single string.

EXAMPLE 3

Read-File -Path 'C:\Path\to\my\file' -MaximumRetries 10 -RetryDelayMilliseconds 1000

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

EXAMPLE 4

Read-File -Path 'C:\Path\to\my\file' -ErrorVariable 'readErrors'

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