Reading and writing to files

Writing to files

Writing to a file

$lines = @(1,"2",3,(get-date))
$path = "c:\d\myfile.txt"
$lines | Out-File -FilePath $path

Appending to a file

$lines = @(1,"2",3,(get-date))
$path = "c:\d\myfile.txt"
$lines | Out-File -FilePath $path -Append

Alternatively, you can use set-content

$lines = @(1,"2",3,(get-date))
$path = "c:\d\myfile.txt"
$lines | set-content -Path $path

Reading from a file

$lines = get-content -Path $path
foreach($line in $lines) {
    if ($line -imatch "^[0-9]+$") {
        write-host $line
    }
}

Writing to a file very fast (Using Dotnet stream)

$path = "c:\d\myfile.txt"
$stream = [System.IO.StreamWriter]::new($path)
foreach ($p in (0..100000)) {
    $stream.WriteLine("$p")
}
$stream.close()

Reading from a file very fast (Using Dotnet stream)

$path = "c:\d\myfile.txt"
$stream = [System.IO.StreamReader]::new($path)
while( -not $stream.EndOfStream) {
    $value =  [int]($stream.ReadLine())
    if (($value%10000) -eq 0) {
        write-host $value
    }
}
$stream.close()

Tailing a log

$path = "c:\d\myfile.txt"
get-content -Path $path -tail 20 -wait

add some content while it is watching

$path = "c:\d\myfile.txt"
"Some new line in the log" | Out-File -Append $path -encoding Utf8

Pipeline write

Overwrite

$path = "c:\d\myfile.txt"
"hello" > $path

Append

$path = "c:\d\myfile.txt"
"hello" >> $path

results matching ""

    No results matching ""