PoshCode Archive  Artifact [402543f19f]

Artifact 402543f19f6522fd9049707843cbb4c6a4b9fc8248c2ac7147e193620e12c90e:

  • File Unix-Out-File.ps1 — part of check-in [80af922bbd] at 2018-06-10 14:12:42 on branch trunk — Write line to file with Unix Line Endings (user: Bruno Martins size: 1893)

# encoding: ascii
# api: powershell
# title: Unix Out-File
# description: Write line to file with Unix Line Endings
# version: 0.1
# type: function
# author: Bruno Martins
# license: CC0
# function: Out-UnixFile
# x-poshcode-id: 6308
# x-archived: 2016-04-22T21:36:10
# x-published: 2016-04-18T17:44:00
#
#
function Out-UnixFile
{
    Param(

        [Parameter( Mandatory = $True )]
        [string]
        $FilePath,

        [Parameter( Mandatory = $True, ValueFromPipeline = $True )]
        [string[]]
        $InputObject,

        [switch]
        $Append = $False
    )

    BEGIN
    {
        $Fs = $Null
        $Sw = $Null
        
        Try
        {
            If( -not( Test-Path $FilePath ) )
            {
                $result = New-Item -Path $FilePath -ItemType File -ErrorAction Stop
            }

            $Encoding = New-Object System.Text.UTF8Encoding

            If( $Append )
            {
                $FileMode = [System.IO.FileMode]::Append
            }
            Else
            {
                $FileMode = [System.IO.FileMode]::Open
            }

            $Fs = New-Object -TypeName System.IO.FileStream( $FilePath, $FileMode )
            $Sw = New-Object -TypeName System.IO.StreamWriter( $Fs, $Encoding )
        }
        Catch
        {
            Throw
        }
    }

    PROCESS
    {

        Try
        {
            ForEach( $Line in $InputObject )
            {
                $Sw.Write( "$( $line )`n" )
            }
        }
        Catch
        {
            If( $Sw -ne $Null )
            {
                $Sw.Close()
            }

            If( $Fs -ne $Null )
            {
                $Fs.Close()
            }

            Throw
        }
    }

    END
    {
        $Sw.Close()
        $Fs.Close()
    }
}