Friday, August 19, 2016

PowerShell - Manipulate files

# Declare variables
$timestamp = Get-Date -format "yyyy-mm-dd_HH-mm-ss"

$path = "c:\temp"

$filename = $timestamp + ".txt"
$fullFilename = $path + "\" + $filename

$fullFilename

# Create a file
New-Item -Path $path -Name $filename -ItemType "File"

# Does file exist?
Write-Host "Does file $fullFilename exist?"
Test-Path $fullFilename

# Remove it
rm $fullFilename

# Now check again
# Does file exist?
Write-Host "Does file $fullFilename still exist?"
Test-Path $fullFilename

# Re-create the file so we can play with it
New-Item -Path $path -Name $filename -ItemType "File"

# Add text to file
Add-Content $fullFilename "Hello World"

# Copy the file
$newFilename = $timestamp + ".new"
$newFullFilename = $path + "\" + $newFilename

Copy-Item $fullFilename $newFullFilename

# Remove the new file
rm $newFullFilename

# Move the file
Move-Item $fullFilename $newFullFilename

# Read the file
$stuff = Get-Content $newFullFilename

# Displays 'Hello World' (the content of the file)
Write-Host $stuff

rm $newFullFilename