Types/OpenPackage.Part/Import.ps1

<#
.SYNOPSIS
    Imports content into a part
.DESCRIPTION
    Imports content into an Open Package part.
#>

param(
# The content to import.
# If this is a byte array, import bytes
# If this is a file, will import the contents of the file.
[PSObject]
$InputObject
)

# If the input was bytes, or can be cast to bytes
if ($inputObject -is [byte[]] -or (
    $inputObject -is [object[]] -and 
    $InputObject -as [byte[]]
)) {
    # get a buffer
    $Buffer = [byte[]]$InputObject
    # get our stream
    $partStream = $this.GetStream()
    # fix the size
    $partStream.SetLength($Buffer.Length)
    # and write to the stream.
    $null = $partStream.Write($Buffer, 0, $Buffer.Length)    
    # Then clean up
    $partStream.Close()
    $partStream.Dispose()
    return # and return.
}

# If the input object existed as a path
if (Test-Path $inputObject) {
    # set the inputobject to what we get
    $InputObject = Get-Item $InputObject
}

# If we are importing from a file
if ($inputObject -is [IO.FileInfo]) {
    # try to open it for shared read
    $openedFile = $InputObject.Open('Open', 'Read', 'Read')
    # if we could not
    if (-not $openedFile) {
        # return
        return
    }
    # Get our stream,
    $partStream = $this.GetStream()
    # zero it's length,
    $partStream.SetLength(0)
    # copy the file to our stream.
    $openedFile.CopyTo($partStream)
    # Then, close up
    $partStream.Close()
    $partStream.Dispose()
    $openedFile.Close()
    $openedFile.Dispose()
    return # and return.
}

# If we have a writer for this part
if ($this.Writer) {
    # try to write this file's contents
    $this.Write($InputObject)
} else {
    # otherwise, write a warning.
    Write-Warning "No writer found for $InputObject"
}