Types/OpenPackage.Part/WriteText.ps1

<#
.SYNOPSIS
    Writes Part Content as Text
.DESCRIPTION
    Writes Package Part Content as Text
.NOTES

#>

[Reflection.AssemblyMetadata(
    # This should automatically apply to .txt files, modelfiles, and dockerfiles.
    'FilePattern', 
    '(?>[/\.]Dockerfile|[/\.]Modelfile|\.txt|\.svg|\.xml)$'
)]
[Reflection.AssemblyMetadata(
    # This should automatically apply to any text/ content types
    'ContentTypePattern', 
    '^text/'
)]
[Reflection.AssemblyMetadata(
    # This should automatically apply to any xml content types
    'ContentTypePattern', 
    '[/\+]xml'
)]
[Reflection.AssemblyMetadata(
    # This should automatically apply to any json content types
    'ContentTypePattern', 
    '[/\+]json'
)]
[Reflection.AssemblyMetadata(
    # This has a higher order, indicating it should be run later than most.
    'Order', 
    100
)]
param(
# The object to write.
[Alias('Input','Content','Text')]
[PSObject]
$InputObject,

<#

Any options used to write the object

Supported Options:

|Option|Description|
|-|-|
|Encoding|The text encoding|
|Stream|Optional destination stream|
#>


[Collections.IDictionary]
$Option = [Ordered]@{}
)

# If there is no part, return
$part = $this
if (-not $part) { return }

if (-not $option.Encoding) {
    $option.Encoding = [Text.Encoding]::UTF8
}


if (
    # If we provide an optional stream
    $option.Stream -is [IO.Stream] -and
    # and it is writeable
    $option.Stream.CanWrite
) {
    # Then we will write to the stream.

    # Get the bytes we will write
    $bytes = $Option.Encoding.GetBytes("$InputObject")
    # and write them to the stream.
    $option.Stream.Write($bytes,0, $bytes.Length)
    # * The caller gave us the stream
    # * The caller should dispose of it sometime.
    # We can just return.
    return
}

# If no `-Option @{Stream}` was passed
# Then we are writing to this part (or trying to).
$partStream = $part.GetStream('Open','ReadWrite')
# If we can not write, return now.
if (-not $partStream) { return }

# Otherwise, zero out the length
$partStream.SetLength(0)

# Get the bytes we will write
$bytes = $Option.Encoding.GetBytes("$InputObject")

# Write the bytes to the stream,
$partStream.Write($bytes, 0, $bytes.Length)
$partStream.Close() # close,
$partStream.Dispose() # and dispose.