Types/OpenPackage.Part/Export.ps1

<#
.SYNOPSIS
    Exports package parts
.DESCRIPTION
    Exports a part from a package.
    
    This will write the part to a file on disk.
#>

param(
# The export path
[Parameter(Mandatory)]
[string]
$Path
)

if (-not $this.Uri -and -not $this.GetStream) {
    return
}

# The location may already exist
$outputFiles = if (Test-Path $path) {
    # If it does, get the location
    foreach ($foundItem in Get-Item $path) {
        # If it is a file, we are writing directly to it.
        if ($foundItem -is [IO.FileInfo]) {
            $foundItem
        } elseif ($foundItem -is [IO.DirectoryInfo]) {
            # If it is a directory, put the output in that directory,
            $outputPath = Join-Path $foundItem.FullName @(
                # use the last segment as the file name.
                $this.Uri -split '/' -ne ''
            )[-1]
            New-Item -ItemType File -Path $outputPath -Force                
        }
    }
} else {
    # if it does not exist, create a new file.
    New-Item -ItemType File -Path $Path
}

# If we don't have any output files at this point, something is wrong
# so return.
if (-not $outputFiles) { return }
# Go over each output file
foreach ($outputFile in $outputFiles) {
    # Open it for writing
    $openedFile = $outputFile.OpenWrite()    
    if (-not $openedFile) { continue }
    # zero out the length
    $openedFile.SetLength(0)
    # Open our stream for read
    $partStream = $this.GetStream('Open', 'Read')
    # copy it to the file
    $partStream.CopyTo($openedFile)
    # and close up.
    $partStream.Close()
    $partStream.Dispose()
    $openedFile.Close()
    $openedFile.Dispose()
}