File Input Output in Powershell

Published on 10 May 2025 (Updated: 10 May 2025)

Welcome to the File Input Output in Powershell page! Here, you'll find the source code for this program as well as a description of how the program works.

Current Solution

function Set-File([string]$Filename) {
    try {
        $StreamWriter = [IO.StreamWriter]::new($FileName)
        $StreamWriter.WriteLine("Hello, PowerShell!")
        $StreamWriter.WriteLine("A line here")
        $StreamWriter.WriteLine("A line there")
        $StreamWriter.WriteLine("Goodbye, PowerShell!")
        $true
    } catch {
        Write-Host "Cannot write to file ${Filename}: $($_.Exception.Message)"
        $false
    } finally {
        if ($StreamWriter) {
            $StreamWriter.Close()
            $StreamWriter.Dispose()
        }
    }
}

function Get-File([string]$Filename) {
    try {
        foreach ($Line in Get-Content -Path $Filename -ErrorAction Stop) {
            Write-Host $Line
        }
        $true
    } catch {
        Write-Host "Cannot read from file ${Filename}: $($_.Exception.Message)"
        $false
    }
}

$Filename = "output.txt"
if (-not (Set-File($Filename))) {
    Exit 1
}

if (-not (Get-File($Filename))) {
    Exit 1
}

File Input Output in Powershell was written by:

If you see anything you'd like to change or update, please consider contributing.

How to Implement the Solution

No 'How to Implement the Solution' section available. Please consider contributing.

How to Run the Solution

No 'How to Run the Solution' section available. Please consider contributing.