Commands/Lock-OpenPackage.ps1

function Lock-OpenPackage
{
    <#
    .SYNOPSIS
        Locks an Open Package
    .DESCRIPTION
        Locks an Open Package.
        
        Closes the package and copies it into a read-only package.
    .NOTES
        This helps prevent any drift in the package and limit access in server scenarios.
    .EXAMPLE
        # Import OP, make it a package, and lock it
        Import-Module OP -PassThru |
            Get-OpenPackage |
            Lock-OpenPackage
    .EXAMPLE
        # Import OP, make it a package, and lock it
        impo OP -PassThru | op | lkop
    #>

    [CmdletBinding(ConfirmImpact='Medium')]
    [Alias('Lock-OP', 'lkop','lkOpenPackage')]
    param(
    # The input object. This should be a package.
    [Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName)]
    [Alias('Package')]
    [PSObject]
    $InputObject        
    )

    process {
        # If the input is not a package
        if ($InputObject -isnot [IO.Packaging.Package]) {
            return $InputObject # pass it thru.
        }
        
        # If the file access is read, we're already locked
        if ($inputObject.FileOpenAccess -eq 'Read') {
            return $inputObject # so return the current object.
        }
        
        # If the input has no memory stream
        if ($InputObject.MemoryStream -isnot [IO.MemoryStream]) {
            return $InputObject # pass it thru
        }

        # To read the stream we need to close the package.
        $InputObject.Close() # this also makes the current package useless
        # Then we have to seek to the start of the stream
        $null = $InputObject.MemoryStream.Seek(0,'begin')
        # and create a new stream from the old.
        $newStream = [IO.MemoryStream]::new(
            $InputObject.MemoryStream.ToArray()
        )
        # Then close and dispose of the memory stream.
        $InputObject.MemoryStream.Close()
        $InputObject.MemoryStream.Dispose()

        # Create a new package from our new stream, as a read only package.
        $newPackage = [IO.Packaging.Package]::Open($newStream, 'Open', 'Read')
        $newPackage | Add-Member NoteProperty MemoryStream $newStream -Force
        
        $newPackage
    }
}