PowerShell利用Curl发送请求 前言. For Linux distributions that aren't officially supported, you can try to install PowerShell using the PowerShell Snap Package.You can also try deploying PowerShell binaries directly using the Linux tar.gz archive, but you would need to set up the necessary dependencies based on the OS in separate steps. Officially supported platform releases for PowerShell 7.1. In PowerShell curl is a built in alias to Invoke-WebRequest cmdlet. And aliases have priority in command resolution. And aliases have priority in command resolution. To solve your problem you have more specifically, use curl.exe instead of curl, so command not resolved to alias. Yeahh ik that curl is an alias for invoke-werequest in powershell I'm just confused as to how I could get it to download without the filename as if u try just using curl it simply doesn't work properly – Lucas Sep 8 '19 at 23:41.
The Invoke-RestMethod cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes.
Sends an HTTP or HTTPS request to a RESTful web service.
Syntax
Description
The Invoke-RestMethod
cmdlet sends HTTP and HTTPS requests to Representational State Transfer(REST) web services that return richly structured data.
PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returnsthe Item or Entry XML nodes. For JavaScript Object Notation (JSON) or XML, PowerShell converts, ordeserializes, the content into [PSCustomObject]
objects.
Note
When the REST endpoint returns multiple objects, the objects are received as an array. If you pipethe output from Invoke-RestMethod
to another command, it is sent as a single [Object[]]
object. The contents of that array are not enumerated for the next command on the pipeline.
This cmdlet is introduced in Windows PowerShell 3.0.
Beginning in PowerShell 7.0, Invoke-RestMethod
supports proxy configuration defined by environmentvariables. See the Notes section of this article.
Examples
Example 1: Get the PowerShell RSS feed
This example uses the Invoke-RestMethod
cmdlet to get information from the PowerShell Blog RSSfeed. The command uses the Format-Table
cmdlet to display the values of the Title andpubDate properties of each blog in a table.
Example 2: Run a POST request
In this example, a user runs Invoke-RestMethod
to do a POST request on an intranet website in theuser's organization.
The credentials are prompted for and then stored in $Cred
and the URL that will be access isdefined in $Url
.
The $Body
variable describes the search criteria, specifies CSV as the output mode, and specifiesa time period for returned data that starts two days ago and ends one day ago. The body variablespecifies values for parameters that apply to the particular REST API with which Invoke-RestMethod
is communicating.
The Invoke-RestMethod
command is run with all variables in place, specifying a path and file namefor the resulting CSV output file.
Example 3: Follow relation links
Some REST APIs support pagination via Relation Links perRFC5988. Instead of parsing the header to get the URLfor the next page, you can have the cmdlet do this for you. This example returns the first two pagesof issues from the PowerShell GitHub repository.
Example 4: Simplified Multipart/Form-Data Submission
Some APIs require multipart/form-data
submissions to upload files and mixed content. This exampledemonstrates how to update a user's profile.
The profile form requires these fields: firstName
, lastName
, email
, avatar
, birthday
, andhobbies
. The API is expecting an image for the user profile pic to be supplied in the avatar
field. The API will also accept multiple hobbies
entries to be submitted in the same form.
When creating the $Form
HashTable, the key names are used as form field names. By default, thevalues of the HashTable will be converted to strings. If a System.IO.FileInfo
value is present,the file contents will be submitted. If a collection such as arrays or lists are present, the formfield will be submitted multiple times.
By using Get-Item
on the avatar
key, the FileInfo
object will be set as the value. The resultis that the image data for jdoe.png
will be submitted.
By supplying a list to the hobbies
key, the hobbies
field will be present in the submissionsonce for each list item.
Example 5: Pass multiple headers
APIs often require passed headers for authentication or validation. This example demonstrates, howto pass multiple headers from a hash-table
to a REST API.
Example 6: Enumerate returned items on the pipeline
GitHub returns multiple objects an array. If you pipe the output to another command, it is sent as asingle [Object[]]
object.
To enumerate the objects into the pipeline, pipe the results to Write-Output
or wrap the cmdlet inparentheses. The following example counts the number of objects returned by GitHub. Then counts thenumber of objects enumerated to the pipeline.
Parameters
Allows sending of credentials and secrets over unencrypted connections. By default, supplyingCredential or any Authentication option with a Uri that does not begin with https://
will result in an error and the request will abort to prevent unintentionally communicating secretsin plain text over unencrypted connections. To override this behavior at your own risk, supply theAllowUnencryptedAuthentication parameter.
Warning
Using this parameter is not secure and is not recommended. It is provided only for compatibilitywith legacy systems that cannot provide encrypted connections. Use at your own risk.
This feature was added in PowerShell 6.0.0.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the explicit authentication type to use for the request. The default is None.Authentication can't be used with UseDefaultCredentials.
Available Authentication Options:
None
: This is the default option when Authentication is not supplied. No explicitauthentication will be used.Basic
: Requires Credential. The credentials will be used to send an RFC 7617 BasicAuthenticationAuthorization: Basic
header in the format ofbase64(user:password)
.Bearer
: Requires Token. Will send and RFC 6750Authorization: Bearer
header with thesupplied token. This is an alias for OAuthOAuth
: Requires Token. Will send an RFC 6750Authorization: Bearer
header with thesupplied token. This is an alias for Bearer
Supplying Authentication will override any Authorization
headers supplied to Headers orincluded in WebSession.
This feature was added in PowerShell 6.0.0.
Type: | WebAuthenticationType |
Accepted values: | None, Basic, Bearer, OAuth |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the body of the request. The body is the content of the request that follows the headers.You can also pipe a body value to Invoke-RestMethod
.
The Body parameter can be used to specify a list of query parameters or specify the content ofthe response.
When the input is a GET request, and the body is an IDictionary
(typically, a hash table), thebody is added to the Uniform Resource Identifier (URI) as query parameters. For other request types(such as POST), the body is set as the value of the request body in the standard name=value format.
When the body is a form, or it's the output of another Invoke-WebRequest
call, PowerShell sets therequest content to the form fields.
The Body parameter may also accept a System.Net.Http.MultipartFormDataContent object. Thiswill facilitate multipart/form-data
requests. When a MultipartFormDataContent object issupplied for Body, any content related headers supplied to the ContentType, Headers, orWebSession parameters will be overridden by the content headers of theMultipartFormDataContent
object. This feature was added in PowerShell 6.0.0.
Type: | Object |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the client certificate that is used for a secure web request. Enter a variable thatcontains a certificate or a command or expression that gets the certificate.
To find a certificate, use Get-PfxCertificate
or use the Get-ChildItem
cmdlet in the Certificate(Cert:
) drive. If the certificate isn't valid or doesn't have sufficient authority, the commandfails.
Type: | X509Certificate |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the digital public key certificate (X509) of a user account that has permission to sendthe request. Enter the certificate thumbprint of the certificate.
Certificates are used in client certificate-based authentication. They can be mapped only to localuser accounts; they do not work with domain accounts.
To get a certificate thumbprint, use the Get-Item
or Get-ChildItem
command in the PowerShellCert:
drive.
Note
This feature is currently only supported on Windows OS platforms.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the content type of the web request.
If this parameter is omitted and the request method is POST, Invoke-RestMethod
sets the contenttype to application/x-www-form-urlencoded
. Otherwise, the content type isn't specified in thecall.
ContentType will be overridden when a MultipartFormDataContent
object is supplied forBody.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a user account that has permission to send the request. The default is the current user.
Type a user name, such as User01 or Domain01User01, or enter a PSCredential objectgenerated by the Get-Credential
cmdlet.
Credential can be used alone or in conjunction with certain Authentication parameteroptions. When used alone, it will only supply credentials to the remote server if the remote serversends an authentication challenge request. When used with Authentication options, thecredentials will be explicitly sent.
Credentials are stored in a PSCredentialobject and the password is stored as a SecureString.
Note
For more information about SecureString data protection, seeHow secure is SecureString?.
Type: | PSCredential |
Position: | Named |
Default value: | Current user |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies custom method used for the web request. This can be used with the Request Method requiredby the endpoint is not an available option on the Method. Method and CustomMethod cannotbe used together.
Example:
Invoke-RestMethod -uri 'https://api.contoso.com/widget/' -CustomMethod 'TEST'
This makes a TEST
HTTP request to the API.
This feature was added in PowerShell 6.0.0.
Type: | String |
Aliases: | CM |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the cmdlet sets the KeepAlive value in the HTTP header to False. By default,KeepAlive is True. KeepAlive establishes a persistent connection to the server to facilitatesubsequent requests.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates the cmdlet should follow relation links.
Some REST APIs support pagination via Relation Links perRFC5988. Instead of parsing the header to get the URLfor the next page, you can have the cmdlet do this for you. To set how many times to follow relationlinks, use the MaximumFollowRelLink parameter.
When using this switch, the cmdlet returns a collection of pages of results. Each page of resultsmay contain multiple result items.
This feature was added in PowerShell 6.0.0.
Type: | SwitchParameter |
Aliases: | FL |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Converts a dictionary to a multipart/form-data
submission. Form may not be used with Body.If ContentType will be ignored.
The keys of the dictionary will be used as the form field names. By default, form values will beconverted to string values.

If the value is a System.IO.FileInfo object, then the binary file contents will be submitted.The name of the file will be submitted as the filename
. The MIME will be set asapplication/octet-stream
. Get-Item
can be used to simplify supplying the System.IO.FileInfoobject.
$Form = @{resume = Get-Item 'c:UsersjdoeDocumentsJohn Doe.pdf'}
If the value is a collection type, such as an Array or List, the for field will be submittedmultiple times. The values of the list will be treated as strings by default. If the value is aSystem.IO.FileInfo object, then the binary file contents will be submitted. Nested collectionsaren't supported.
$Form = @{tags = 'Vacation', 'Italy', '2017'pictures = Get-ChildItem 'c:UsersjdoePictures2017-Italy'}
In the above example, the tags
field will be supplied three times in the form, once for each ofVacation
, Italy
, and 2017
. The pictures
field will also be submitted once for each file inthe 2017-Italy
folder. The binary contents of the files in that folder will be submitted as thevalues.
This feature was added in PowerShell 6.1.0.
Type: | IDictionary |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the headers of the web request. Enter a hash table or dictionary.
To set UserAgent headers, use the UserAgent parameter. You cannot use this parameter to specifyUser-Agent
or cookie headers.
Content related headers, such as Content-Type
will be overridden when a MultipartFormDataContent
object is supplied for Body.
Type: | IDictionary |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Gets the content of the web request from a file.
Enter a path and file name. If you omit the path, the default is the current location.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies how many times to follow relation links if FollowRelLink is used. A smaller value maybe needed if the REST api throttles due to too many requests. The default value is[Int32]::MaxValue
. A value of 0 (zero) prevents following relation links.
Type: | Int32 |
Aliases: | ML |
Position: | Named |
Default value: | Int32.MaxValue |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies how many times PowerShell redirects a connection to an alternate Uniform ResourceIdentifier (URI) before the connection fails. The default value is 5. A value of 0 (zero) preventsall redirection.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies how many times PowerShell retries a connection when a failure code between 400 and 599,inclusive or 304 is received. Also see RetryIntervalSec parameter for specifying number ofretries.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the method used for the web request. The acceptable values for this parameter are:
Default
Delete
Get
Head
Merge
Options
Patch
Post
Put
Trace
The CustomMethod parameter can be used for Request Methods not listed above.
Type: | WebRequestMethod |
Accepted values: | Default, Get, Head, Post, Put, Delete, Trace, Options, Merge, Patch |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the cmdlet will not use a proxy to reach the destination.
When you need to bypass the proxy configured in Internet Explorer, or a proxy specified in theenvironment, use this switch.
This parameter was introduced in PowerShell 6.0.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Saves the response body in the specified output file. Enter a path and file name. If you omit thepath, the default is the current location. The name is treated as a literal path. Names that containbrackets ([]
) must be enclosed in single quotes ('
).
By default, Invoke-RestMethod
returns the results to the pipeline. To send the results to a fileand to the pipeline, use the Passthru parameter.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Returns the results, in addition to writing them to a file. This parameter is valid only when theOutFile parameter is also used in the command.
Type: | SwitchParameter |
Position: | Named |
Default value: | No output |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates the cmdlet should preserve the Authorization
header, when present, across redirections.
By default, the cmdlet strips the Authorization
header before redirecting. Specifying thisparameter disables this logic for cases where the header needs to be sent to the redirectionlocation.
This feature was added in PowerShell 6.0.0.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Uses a proxy server for the request, rather than connecting directly to the internet resource. Enterthe Uniform Resource Identifier (URI) of a network proxy server.
This feature was added in PowerShell 6.0.0.
Type: | Uri |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a user account that has permission to use the proxy server that is specified by theProxy parameter. The default is the current user.

Type a user name, such as User01 or Domain01User01, User@Domain.Com, or enter aPSCredential
object, such as one generated by the Get-Credential
cmdlet.
This parameter is valid only when the Proxy parameter is also used in the command. You can't usethe ProxyCredential and ProxyUseDefaultCredentials parameters in the same command.
Type: | PSCredential |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the cmdlet uses the credentials of the current user to access the proxy server thatis specified by the Proxy parameter.
This parameter is valid only when the Proxy parameter is also used in the command. You can't usethe ProxyCredential and ProxyUseDefaultCredentials parameters in the same command.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Creates a Response Headers Dictionary and saves it in the value of the specified variable. The keysof the dictionary will contain the field names of the Response Header returned by the web server andthe values will be the respective field values.
This feature was added in PowerShell 6.0.0.
Type: | String |
Aliases: | RHV |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Performs a best effort attempt to resume downloading a partial file. The Resume parameterrequires the OutFile parameter.
Resume only operates on the size of the local file and remote file and performs no othervalidation that the local file and the remote file are the same.
If the local file size is smaller than the remote file size, then the cmdlet will attempt to resumedownloading the file and append the remaining bytes to the end of the file.
If the local file size is the same as the remote file size, then no action is taken and the cmdletassumes the download already completed.
If the local file size is larger than the remote file size, then the local file will be overwrittenand the entire remote file will be completely re-downloaded. This behavior is the same as usingOutFile without Resume.
If the remote server does not support download resuming, then the local file will be overwritten andthe entire remote file will be completely re-downloaded. This behavior is the same as usingOutFile without Resume.
If the local file doesn't exist, then the local file will be created and the entire remote file willbe completely downloaded. This behavior is the same as using OutFile without Resume.
This feature was added in PowerShell 6.1.0.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the interval between retries for the connection when a failure code between 400 and 599,inclusive or 304 is received. Also see MaximumRetryCount parameter for specifying number ofretries.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a variable for which this cmdlet creates a web request session and saves it in the value.Enter a variable name without the dollar sign ($
) symbol.
When you specify a session variable, Invoke-RestMethod
creates a web request session object andassigns it to a variable with the specified name in your PowerShell session. You can use thevariable in your session as soon as the command completes.
Unlike a remote session, the web request session isn't a persistent connection. It's an object thatcontains information about the connection and the request, including cookies, credentials, themaximum redirection value, and the user agent string. You can use it to share state and data amongweb requests.
To use the web request session in subsequent web requests, specify the session variable in the valueof the WebSession parameter. PowerShell uses the data in the web request session object whenestablishing the new connection. To override a value in the web request session, use a cmdletparameter, such as UserAgent or Credential. Parameter values take precedence over values inthe web request session.
You can't use the SessionVariable and WebSession parameters in the same command.
Type: | String |
Aliases: | SV |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Skips certificate validation checks that include all validations such as expiration, revocation,trusted root authority, etc.
Warning
Using this parameter is not secure and is not recommended. This switch is only intended to be usedagainst known hosts using a self-signed certificate for testing purposes. Use at your own risk.
This feature was added in PowerShell 6.0.0.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates the cmdlet should add headers to the request without validation.
This switch should be used for sites that require header values that do not conform to standards.Specifying this switch disables validation to allow the value to be passed unchecked. Whenspecified, all headers are added without validation.
This will disable validation for values passed to the ContentType, Headers, and UserAgentparameters.
This feature was added in PowerShell 6.0.0.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter causes the cmdlet to ignore HTTP error statuses and continue to process responses.The error responses are written to the pipeline just as if they were successful.
This parameter was introduced in PowerShell 7.
Type: | SwitchParameter |
Position: | Named |
Default value: | False |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Sets the SSL/TLS protocols that are permissible for the web request. By default all, SSL/TLSprotocols supported by the system are allowed. SslProtocol allows for limiting to specificprotocols for compliance purposes.
These values are defined as a flag-based enumeration. You can combine multiple values together toset multiple flags using this parameter. The values can be passed to the SslProtocol parameteras an array of values or as a comma-separated string of those values. The cmdlet will combine thevalues using a binary-OR operation. Passing values as an array is the simplest option and alsoallows you to use tab-completion on the values. You may not be able to supply multiple values on allplatforms.
Note
On non-Windows platforms it may not be possible to supply Tls
or Tls12
as an option. Supportfor Tls13
is not available on all operating systems and will need to be verified on a peroperating system basis.
This feature was added in PowerShell 6.0.0 and support for Tls13
was added in PowerShell 7.1.
Type: | WebSslProtocol |
Accepted values: | Default, Tls, Tls11, Tls12, Tls13 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter specifies a variable that's assigned a status code's integer value. The parameter canidentify success messages or failure messages when used with the SkipHttpErrorCheck parameter.
Input the parameter's variable name as a string such as -StatusCodeVariable 'scv'
.
This parameter was introduced in PowerShell 7.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies how long the request can be pending before it times out. Enter a value in seconds. Thedefault value, 0, specifies an indefinite time-out.
Powershell Curl Username Password
A Domain Name System (DNS) query can take up to 15 seconds to return or time out. If your requestcontains a host name that requires resolution, and you set TimeoutSec to a value greater thanzero, but less than 15 seconds, it can take 15 seconds or more before a WebException is thrown, andyour request times out.
Type: | Int32 |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
The OAuth or Bearer token to include in the request. Token is required by certainAuthentication options. It can't be used independently.
Token takes a SecureString
that contains the token. To supply the token, manually use thefollowing:
Invoke-RestMethod -Uri $uri -Authentication OAuth -Token (Read-Host -AsSecureString)
This parameter was introduced in PowerShell 6.0.
Type: | SecureString |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a value for the transfer-encoding HTTP response header. The acceptable values for thisparameter are:
- Chunked
- Compress
- Deflate
- GZip
- Identity
Type: | String |
Accepted values: | chunked, compress, deflate, gzip, identity |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies the Uniform Resource Identifier (URI) of the internet resource to which the web request issent. This parameter supports HTTP, HTTPS, FTP, and FILE values.
This parameter is required. The parameter name (Uri) is optional.
Type: | Uri |
Position: | 0 |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
This parameter has been deprecated. Beginning with PowerShell 6.0.0, all Web requests use basicparsing only. This parameter is included for backwards compatibility only and any use of it willhave no effect on the operation of the cmdlet.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Indicates that the cmdlet uses the credentials of the current user to send the web request. Thiscan't be used with Authentication or Credential and may not be supported on all platforms.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a user agent string for the web request.
The default user agent is similar toMozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.15063; en-US) PowerShell/6.0.0
with slightvariations for each operating system and platform.
To test a website with the standard user agent string that is used by most internet browsers, usethe properties of the PSUserAgent class,such as Chrome, FireFox, InternetExplorer, Opera, and Safari.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Specifies a web request session. Enter the variable name, including the dollar sign ($
).
To override a value in the web request session, use a cmdlet parameter, such as UserAgent orCredential. Parameter values take precedence over values in the web request session. Contentrelated headers, such as Content-Type
, will be also be overridden when aMultipartFormDataContent object is supplied for Body.
Unlike a remote session, the web request session isn't a persistent connection. It's an object thatcontains information about the connection and the request, including cookies, credentials, themaximum redirection value, and the user agent string. You can use it to share state and data amongweb requests.
To create a web request session, enter a variable name, without a dollar sign, in the value of theSessionVariable parameter of an Invoke-RestMethod
command. Invoke-RestMethod
creates thesession and saves it in the variable. In subsequent commands, use the variable as the value of theWebSession parameter.
You can't use the SessionVariable and WebSession parameters in the same command.
Type: | WebRequestSession |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Inputs
You can pipe the body of a web request to Invoke-RestMethod
.
Outputs
System.Int64, System.String, System.Xml.XmlDocument
The output of the cmdlet depends upon the format of the content that is retrieved.
PSObject
If the request returns JSON strings, Invoke-RestMethod
returns a PSObject that represents thestrings.
Notes
Some features may not be available on all platforms.
Because of changes in .NET Core 3.1, PowerShell 7.0 and higher use theHttpClient.DefaultProxyProperty to determine the proxy configuration.
The value of this property is different rules depending on your platform:
- For Windows: Reads proxy configuration from environment variables or, if those are notdefined, from the user's proxy settings.
- For macOS: Reads proxy configuration from environment variables or, if those are not defined,from the system's proxy settings.
- For Linux: Reads proxy configuration from environment variables or, in case those are notdefined, this property initializes a non-configured instance that bypasses all addresses.
The environment variables used for DefaultProxy
initialization on Windows and Unix-based platformsare:
HTTP_PROXY
: the hostname or IP address of the proxy server used on HTTP requests.HTTPS_PROXY
: the hostname or IP address of the proxy server used on HTTPS requests.ALL_PROXY
: the hostname or IP address of the proxy server used on HTTP and HTTPS requests incaseHTTP_PROXY
orHTTPS_PROXY
are not defined.NO_PROXY
: a comma-separated list of hostnames that should be excluded from proxying.
Related Links
cURL is a tool we all find very useful, and if we are PowerShell users, we often want to have the combination of PowerShell and cURL. With PowerShell 3.0, one of the really great CmdLets that is available is Invoke-RestMethod. This handy little CmdLet allows us to now use the PowerShell scripting language to access HTTP resources using the native HTTP methods (GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, OPTIONS, MERGE, PATCH).
If you are familiar with curl, you must be thinking the same thing as I am: this sounds exactly like cURL in PowerShell!
Now, let’s take a look at a step by step guide to get using PowerShell cURL!

The Same Thing as PowerShell cURL!
If you have needed to access HTTP resources in the past, you would usually use a command line tool like cURL to be able to interact with HTTP resources through batch processes and scripts. This works great of course, but not if you are spending most of your time in PowerShell. Now now that we have the ability to use the core Invoke-RestMethod CmdLet, let us quickly review how it works (which is exactly like cURL)
How the cURL PowerShell Equivalent Works
Let’s pretend we need to consume some XML data and render it to a file on our Windows server. The way that we would have done this before with curl would be using the following command line:
curl.exe www.discoposse.com/index.php/feed > C:TempDiscoPosseFeed.xml
Now that was not a difficult thing to deal with, but the point of our exercise is to eliminate unnecessary third party tools and functions where there are native PowerShell CmdLets available. This can be very hand when we want the functionality of curl in a PowerShell script.
This is where our newly available Invoke-RestMethod comes in. By leveraging this CmdLet we no longer need to launch the cURL utility. We can get the same functionality in PowerShell just like curl.
PowerShell cURL Like Command – Example
Now, we will try the new way of doing this.
Our new command we will use to begin is this:
Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -Method Get
Simple enough to begin with. This uses the URI of my news feed and runs the GET method to retrieve it. The default method for the CmdLet is GET so you could choose to leave out the-Method Get parameter.
Now we launch the PowerShell command and see that it writes the output to screen. As it should of course because we haven’t done anything to redirect the output to file yet.
So our next step we do is our usual way of using the pipeline to output to the file system to an XML file.
Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -Method Get | Out-File C:TempDiscoPosseFeed.xml
Now let’s take a look at the file itself to see what we have gotten from the process so far.
It seems that we don’t quite have what we want here doesn’t it? We want the file to be in XML format. After all, the content being read from the HTTP resource is XML output. If you look back at the CmdLet output to screen you will see that it looks the same as our file.
This is our eureka moment! We have somehow rendered the XML into more human readable output. This is a cute little trick, but not what we were after. This is a new “feature” of the Invoke-RestMethod CmdLet that it renders XML output as a list.
The fix for this situation is simple. Rather than using the traditional method of the pipeline to an Out-File CmdLet, we just have to add the -OutFile parameter to the command and this takes care of the output to the file system for us.
Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -Method Get -OutFile C:TempDiscoPosseFeed.xml
Now we open the output file and we will see that it is in the exact format that we would expect an XML stream to be. Much better!
The Power of cURL in PowerShell
Summary: PowerShell cURL – How to Get It!
To review what we have done here, we have used the Invoke-RestMethod CmdLet to perform the Get HTTP method against an available URL and rendered the output to a file. In this case it was an XML file that we have created. We have used PowerShell to do exactly what we would normally do with cURL.
The only downside to this is that it is not yet available because it is only a part of the PowerShell 3.0 environment. Never fear, we aren’t far away from having this in general availability. Then we can leverage this and many of the othe exciting features of PowerShell 3.0 and all it has to offer.
Powershell Curl Parameters
If you are a PowerShell and cURL user, be sure to check out Downloading Text and Binary Objects with cURL.
