Types/OpenPackage/SetContent.ps1
|
<# .SYNOPSIS Sets package content .DESCRIPTION Sets content in an open package. Will overwrite existing entries. #> param( # The package uri [uri] $Uri, # The package content [PSObject] $Content, # The content type [string] $ContentType, # Any options [Alias('Options')] [Collections.IDictionary] $Option = [Ordered]@{} ) $part = if ($InputObject.PartExists($uri)) { $InputObject.GetPart($uri) } else { $InputObject.CreatePart($uri, $ContentType) } if (-not $?) { return } if ($part.Writer -and $part.Write) { $part.Write($Content, $Option) return } # Get the stream $partStream = $part.GetStream() if (-not $partStream) { return } # zero out the stream, so we do not underwrite content $partStream.SetLength(0) # First see if the content is a byte[] if ($content -is [byte[]]) { # if so, just write it $partStream.Write($content, 0, $content.Length) } # If the content is a stream, elseif ($content -is [IO.Stream]) { # copy it in. $content.CopyTo($partStream) } # If the content was xml or could be, elseif ($content -is [xml] -or ($contentXml = $content -as [xml])) { if ($contentXml) { $content = $contentXml } $content.Save($partStream) } elseif ($content -is [string]) { # Put strings in as a byte array. $buffer = $OutputEncoding.GetBytes($content) $partStream.Write($buffer, 0, $buffer.Length) } elseif ($contentBytes = $content -as [byte[]]) { # Bytes are obviously a byte array $partStream.Write($contentBytes, 0, $contentBytes.Length) } elseif ($ContentType -match '[/\+]json') { # Explicitly typed json can be converted to json $buffer = $OutputEncoding.GetBytes((ConvertTo-Json -InputObject $content -Depth 10)) $partStream.Write($buffer, 0, $buffer.Length) } else { # and everything else is stringified $buffer = $OutputEncoding.GetBytes("$content") $partStream.Write($buffer, 0, $buffer.Length) } # Close the part stream $partStream.Close() |