Programming Fundamentals/Files/PowerShell
Appearance
files.ps1
[edit | edit source]# This program creates a file, adds data to the file, displays the file,
# appends more data to the file, displays the file, and then deletes the file.
# It will not run if the file already exists.
#
# References:
# https://en.wikiversity.org/wiki/PowerShell/File_System
function Create-File($filename)
{
Add-Content -Path $filename -Value "C`tF"
for($celsius = 0; $celsius -le 50; $celsius++)
{
$fahrenheit = $celsius * 9 / 5 + 32
$line = $celsius.ToString('0.0') + "`t" + $fahrenheit.ToString('0.0')
Add-Content -Path $filename -Value $line
}
}
function Read-File($filename)
{
$content = Get-Content -Path $filename
foreach ($line in $content)
{
Write-Output $line
}
}
function Append-File($filename)
{
for($celsius = 51; $celsius -le 100; $celsius++)
{
$fahrenheit = $celsius * 9 / 5 + 32
$line = $celsius.ToString('0.0') + "`t" + $fahrenheit.ToString('0.0')
Add-Content -Path $filename -Value $line
}
}
function Delete-File($filename)
{
Remove-Item -Path $filename
}
function Main()
{
$filename = "~file.txt"
if (Test-Path -Path $filename)
{
Write-Host 'File already exists.'
}
else
{
Create-File $filename
Read-File $filename
Append-File $filename
Read-File $filename
Delete-File $filename
}
}
Main
Try It
[edit | edit source]Copy and paste the code above into one of the following free online development environments or use your own PowerShell compiler / interpreter / IDE.
Online
[edit | edit source]- There are some options, but none are fully functional at this time.