Private/Out-PASFile.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
function Out-PASFile { <# .SYNOPSIS Writes a Byte Array to a file .DESCRIPTION Takes a Byte Array from a web response and writes it to a file. Suggested filename from Content-Disposition Header is used for naming. .PARAMETER InputObject Content and Header properties from a web response .PARAMETER Path Output folder for the file. Defaults to $ENV:TEMP .EXAMPLE Out-PASFile -InputObject $result #> [CmdletBinding(SupportsShouldProcess)] param( [parameter( Mandatory = $false, ValueFromPipelinebyPropertyName = $true )] $InputObject, [parameter( Mandatory = $false, ValueFromPipelinebyPropertyName = $true )] [string]$Path ) Begin { } Process { If (-not ($Path)) { #Default to TEMP if path not provided $Path = [Environment]::GetEnvironmentVariable('Temp') } #Get filename from Content-Disposition Header element. $FileName = ($InputObject.Headers['Content-Disposition'] -split 'filename=')[1] -replace '"' #Define output path $OutputPath = Join-Path $Path $FileName if ($PSCmdlet.ShouldProcess($OutputPath, 'Save File')) { try { #Command Parameters $output = @{ Path = $OutputPath Value = $InputObject.Content Encoding = 'Byte' } If (Test-IsCoreCLR) { #amend parameters for splatting if we are in Core $output.Add('AsByteStream', $true) $output.Remove('Encoding') } #write file Set-Content @output -ErrorAction Stop #return file object Get-Item -Path $OutputPath } catch { #throw the error $PSCmdlet.ThrowTerminatingError( [System.Management.Automation.ErrorRecord]::new( "Error Saving $OutputPath", $null, [System.Management.Automation.ErrorCategory]::NotSpecified, $PSItem ) ) } } } End { } } |