Skip to content

Instantly share code, notes, and snippets.

@AlexSen
Last active June 4, 2017 21:21
Show Gist options
  • Select an option

  • Save AlexSen/81eed59cb3f68b8e04129d0c795867ff to your computer and use it in GitHub Desktop.

Select an option

Save AlexSen/81eed59cb3f68b8e04129d0c795867ff to your computer and use it in GitHub Desktop.
Function Get-MultipartRequestParameters(){
<#
.SYNOPSIS
Function returnds object withi contains parameters needed for invoking CmdLets like Invoke-WebRequest or Invoke-RESTRequest
.DESCRIPTION
Function returnds object withi contains parameters needed for invoking CmdLets like Invoke-WebRequest or Invoke-RESTRequest.
Function automatically recognizes file paths in values and determinates it's Content-Type
.EXAMPLE
$Attachments = @(
@{attachment = $FileFullPath1},
@{attachment = $FileFullPath2},
@{somekey = "This is value"},
)
$Params = Get-MultipartRequestParameters -Url $Uri -Attachments $Attachments
Invoke-WebRequest @Params
.PARAMETER Uri
Url which would be used in Uri parameter of Invoke-WebRequest or Invoke-RESTRequest CmdLet
.PARAMETER Headers
If your request have to have any headers - feel free to pass it here as @{}
.PARAMETER BodyData
Array of hashtables of all Form Body parameters which you plan to pass
#>
param(
[Parameter(Mandatory=$True)]
[Uri]
$Uri
,
[HashTable]
$Headers = @{}
,
[Parameter(Mandatory=$True)]
[Array]
$BodyData
)
# Define global variables
$LF = "`r`n"
$boundary = [System.Guid]::NewGuid().ToString()
$BodyLinesArray = @()
ForEach ( $BodyDataItem in $BodyData )
{
# Check if it's file
if ( Test-Path -Path $BodyDataItem.Values )
{
$FileItem = Get-Item -LiteralPath $BodyDataItem.Values
$FileContentType = [System.Web.MimeMapping]::GetMimeMapping($FileItem.Name)
$FileBytes = [IO.File]::ReadAllBytes($BodyDataItem.Values)
$FileContentAsString = ([System.Text.Encoding]::GetEncoding("iso-8859-1")).GetString($fileBytes)
# Add information to main body lines
$BodyLinesArray += "--$boundary"
$BodyLinesArray += "Content-Disposition: form-data; name=`"$($BodyDataItem.Keys)`"; filename=`"$($FileItem.Name)`""
$BodyLinesArray += "Content-Type: $FileContentType$LF"
$BodyLinesArray += $FileContentAsString
}
else
{
# Add information to main body lines
$BodyLinesArray += "--$boundary"
$BodyLinesArray += "Content-Disposition: form-data; name=`"$($BodyDataItem.Keys)`"$LF"
$BodyLinesArray += ($BodyDataItem.Values)
}
}
# Add last bounder to Body
$BodyLinesArray += "--$boundary--$LF"
$BodyLines = $BodyLinesArray -join $LF
# Add ContentType to header
$Headers.Add("Content-Type", "multipart/form-data; boundary=`"$boundary`"")
# Prepare response
$Response = @{
Uri = $Uri
Method = "POST"
Headers = $Headers
Body = $BodyLines
}
Return $Response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment