internal/functions/add-webrequestcontentfromfile.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

<#
    .SYNOPSIS
        Add content from file to a Web Request
         
    .DESCRIPTION
        Read the content from a file and put it into the Web Request object
         
    .PARAMETER WebRequest
        The Web Request object that you want to add the content of the file to
         
    .PARAMETER Path
        Path to the file you want to add to the Web Request object
         
    .EXAMPLE
        PS C:\> $request = New-WebRequest -Url "https://usnconeboxax1aos.cloud.onebox.dynamics.com/api/connector/enqueue/123456789" -Action "POST" -AuthenticationToken "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOi....."
        PS C:\> Add-WebRequestContentFromFile -WebRequest $request -Path "c:\temp\d365fo.tools\dmfpackage.zip"
         
        This will add the file content to the Web Request.
        It will create a new Web Request object.
        It will use the "c:\temp\d365fo.tools\dmfpackage.zip" path to read the file content.
         
    .LINK
        New-WebRequest
         
    .NOTES
        Tags: Request, DMF, Package, Packages
         
        Author: Mötz Jensen (@Splaxi)
         
#>


function Add-WebRequestContentFromFile {
    [CmdletBinding()]
    [OutputType()]
    param (
        [Parameter(Mandatory = $true)]
        [System.Net.WebRequest] $WebRequest,

        [Parameter(Mandatory = $true)]
        [string] $Path

    )

    if (-not (Test-PathExists -Path $Path -Type Leaf)) { return }

    try {
        Write-PSFMessage -Level Debug -Message "Working on file: $Path" -Target $Path
    
        $fileStream = New-Object System.IO.FileStream($Path, [System.IO.FileMode]::Open)
        
        Write-PSFMessage -Level Debug -Message "Length $($fileStream.Length)"
        
        $WebRequest.ContentLength = $fileStream.Length
        $stream = $WebRequest.GetRequestStream()
        $fileStream.CopyTo($stream)
        $fileStream.Flush()
        $fileStream.Close()
    }
    catch {
        Write-PSFMessage -Level Critical -Message "Exception while adding the file content to the WebRequest" -Exception $_.Exception
        Stop-PSFFunction -Message "Stopping" -StepsUpward 1
    }
}