Saturday, August 20, 2016

PowerShell - Read and Write Text Files

# Write, append, and read files

# First set up some variables
$filename = "c:\temp\file.txt"
$myText = "Hello World"
$mySecondLine = "Goodbye World"
$myThirdLine = "My third line"
$myFourthLine = "My fourth line"

# Create file
$myText > $filename

# Another way
$myText | Set-Content $filename

# Another way
$myText | Out-File $filename

#################################

# Append to file
$mySecondLine >> $filename

# Another way
$myThirdLine | Add-Content $filename

# Another way
$myFourthLine | Out-File $filename -Append

#################################

# Read content

$myVar = Get-Content $filename

# Dashes
Write-Host $('-' * 70)

# Display content
$myVar

# Display first line
Write-Host $('-' * 70)
$myVar[0]

# Display second line
Write-Host $('-' * 70)
$myVar[1]

# Display first three lines
Write-Host $('-' * 70)
$myVar[0..2]

# Display the last line
Write-Host $('-' * 70)
$myVar[-1]

# Display the last three lines
Write-Host $('-' * 70)
$myVar[-1..-3]