|
| 1 | +'use strict' |
| 2 | + |
| 3 | +var CodeBuilder = require('../../helpers/code-builder') |
| 4 | + |
| 5 | +module.exports = function (source, options) { |
| 6 | + var code = new CodeBuilder() |
| 7 | + var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ] |
| 8 | + |
| 9 | + if (methods.indexOf(source.method.toUpperCase()) === -1) { |
| 10 | + return 'Method not supported' |
| 11 | + } |
| 12 | + |
| 13 | + var commandOptions = [] |
| 14 | + |
| 15 | + // Add headers, including the cookies |
| 16 | + var headers = Object.keys(source.headersObj) |
| 17 | + |
| 18 | + // construct headers |
| 19 | + if (headers.length) { |
| 20 | + code.push('$headers=@{}') |
| 21 | + headers.forEach(function (key) { |
| 22 | + if (key !== 'connection') { // Not allowed |
| 23 | + code.push('$headers.Add("%s", "%s")', key, source.headersObj[key]) |
| 24 | + } |
| 25 | + }) |
| 26 | + commandOptions.push('-Headers $headers') |
| 27 | + } |
| 28 | + |
| 29 | + // construct cookies |
| 30 | + if (source.cookies.length) { |
| 31 | + code.push('$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession') |
| 32 | + |
| 33 | + source.cookies.forEach(function (cookie) { |
| 34 | + code.push('$cookie = New-Object System.Net.Cookie') |
| 35 | + |
| 36 | + code.push("$cookie.Name = '%s'", cookie.name) |
| 37 | + code.push("$cookie.Value = '%s'", cookie.value) |
| 38 | + code.push("$cookie.Domain = '%s'", source.uriObj.host) |
| 39 | + |
| 40 | + code.push('$session.Cookies.Add($cookie)') |
| 41 | + }) |
| 42 | + commandOptions.push('-WebSession $session') |
| 43 | + } |
| 44 | + |
| 45 | + if (source.postData.text) { |
| 46 | + commandOptions.push("-ContentType '" + source.allHeaders['content-type'] + "'") |
| 47 | + commandOptions.push("-Body '" + source.postData.text + "'") |
| 48 | + } |
| 49 | + |
| 50 | + code.push("$response = Invoke-WebRequest -Uri '%s' -Method %s %s", source.fullUrl, source.method, commandOptions.join(' ')) |
| 51 | + return code.join() |
| 52 | +} |
| 53 | + |
| 54 | +module.exports.info = { |
| 55 | + key: 'webrequest', |
| 56 | + title: 'Invoke-WebRequest', |
| 57 | + link: 'https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Invoke-WebRequest', |
| 58 | + description: 'Powershell Invoke-WebRequest client' |
| 59 | +} |
0 commit comments