This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
Gets content from a web page on the internet.
Invoke-WebRequest [-Uri] <Uri> [-UseBasicParsing] [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-Method <WebRequestMethod>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>]Invoke-WebRequest [-Uri] <Uri> [-UseBasicParsing] [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-Method <WebRequestMethod>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-NoProxy] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>]Invoke-WebRequest [-Uri] <Uri> -CustomMethod <String> [-UseBasicParsing] [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>]Invoke-WebRequest [-Uri] <Uri> -CustomMethod <String> [-UseBasicParsing] [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-NoProxy] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>]TheInvoke-WebRequest cmdlet sends HTTP and HTTPS requests to a web page or web service. It parsesthe response and returns collections of links, images, and other significant HTML elements.
This cmdlet was introduced in PowerShell 3.0.
Beginning in PowerShell 7.0,Invoke-WebRequest supports proxy configuration defined by environmentvariables. See theNotes section of this article.
Important
The examples in this article reference hosts in thecontoso.com domain. This is a fictitiousdomain used by Microsoft for examples. The examples are designed to show how to use the cmdlets.However, since thecontoso.com sites don't exist, the examples don't work. Adapt the examplesto hosts in your environment.
Beginning in PowerShell 7.4, character encoding for requests defaults to UTF-8 instead of ASCII. Ifyou need a different encoding, you must set thecharset attribute in theContent-Type header.
This example uses theInvoke-WebRequest cmdlet to send a web request to the Bing.com site.
$Response = Invoke-WebRequest -Uri https://www.bing.com/search?q=how+many+feet+in+a+mile$Response.InputFields | Where-Object { $_.Name -like "* Value*"} | Select-Object Name, ValueName Value---- -----From Value 1To Value 5280The first command issues the request and saves the response in the$Response variable.
The second command gets anyInputField where theName property is like"* Value". Thefiltered results are piped toSelect-Object to select theName andValue properties.
This example shows how to use theInvoke-WebRequest cmdlet with a stateful web service.
$LoginParameters = @{ Uri = 'https://www.contoso.com/login/' SessionVariable = 'Session' Method = 'POST' Body = @{ User = 'jdoe' Password = 'P@S$w0rd!' }}$LoginResponse = Invoke-WebRequest @LoginParameters$ProfileResponse = Invoke-WebRequest 'https://www.contoso.com/profile/' -WebSession $SessionThe first call toInvoke-WebRequest sends a sign-in request. The command specifies a value ofSession for the value of theSessionVariable parameter. When the command completes, the$LoginResponse variable contains anBasicHtmlWebResponseObject and the$Session variablecontains aWebRequestSession object. This logs the user into the site.
The second call toInvoke-WebRequest fetches the user's profile, which requires the user be signedinto the site. The session data stored in the$Session variable provides session cookiesto the site created during the login.
This example gets the links in a web page. It uses theInvoke-WebRequest cmdlet to get the webpage content. Then it uses theLinks property of theBasicHtmlWebResponseObject thatInvoke-WebRequest returns, and theHref property of each link.
(Invoke-WebRequest -Uri "https://aka.ms/pscore6-docs").Links.HrefThis example uses theInvoke-WebRequest cmdlet to retrieve the web page content of a PowerShelldocumentation page.
$Response = Invoke-WebRequest -Uri "https://aka.ms/pscore6-docs"$Stream = [System.IO.StreamWriter]::new('.\docspage.html', $false, $Response.Encoding)try { $Stream.Write($Response.Content)} finally { $Stream.Dispose()}The first command retrieves the page and saves the response object in the$Response variable.
The second command creates aStreamWriter to use to write the response content to a file. TheEncoding property of the response object is used to set the encoding for the file.
The final few commands write theContent property to the file then disposes theStreamWriter.
Note that theEncoding property is null if the web request doesn't return text content.
This example uses theInvoke-WebRequest cmdlet upload a file as amultipart/form-datasubmission. The fileC:\document.txt is submitted as the form fielddocument with theContent-Type oftext/plain.
$FilePath = 'C:\document.txt'$FieldName = 'document'$ContentType = 'text/plain'$FileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open)$FileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new('form-data')$FileHeader.Name = $FieldName$FileHeader.FileName = Split-Path -Leaf $FilePath$FileContent = [System.Net.Http.StreamContent]::new($FileStream)$FileContent.Headers.ContentDisposition = $FileHeader$FileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($ContentType)$MultipartContent = [System.Net.Http.MultipartFormDataContent]::new()$MultipartContent.Add($FileContent)$Response = Invoke-WebRequest -Body $MultipartContent -Method 'POST' -Uri 'https://api.contoso.com/upload'Some APIs requiremultipart/form-data submissions to upload files and mixed content. This exampledemonstrates updating a user profile.
$Uri = 'https://api.contoso.com/v2/profile'$Form = @{ firstName = 'John' lastName = 'Doe' email = 'john.doe@contoso.com' avatar = Get-Item -Path 'C:\Pictures\jdoe.png' birthday = '1980-10-15' hobbies = 'Hiking','Fishing','Jogging'}$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $FormThe 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 theavatarfield. The API also accepts multiplehobbies 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 are converted to strings. If aSystem.IO.FileInfo value is present, thefile contents are submitted. If a collection such as arrays or lists are present, the form field issubmitted multiple times.
UsingGet-Item on theavatar key, theFileInfo object is set as the value. The result isthat the image data forjdoe.png is submitted.
By supplying a list to thehobbies key, thehobbies field is present in the submissions once foreach list item.
WhenInvoke-WebRequest encounters a non-success HTTP message (404, 500, etc.), it returns nooutput and throws a terminating error. To catch the error and view theStatusCode you canenclose execution in atry/catch block.
try{ $Response = Invoke-WebRequest -Uri "www.microsoft.com/unkownhost" # This will only execute if the Invoke-WebRequest is successful. $StatusCode = $Response.StatusCode} catch { $StatusCode = $_.Exception.Response.StatusCode.value__}$StatusCode404The terminating error is caught by thecatch block, which retrieves theStatusCode from theException object.
TheInvoke-WebRequest cmdlet can only download one file at a time. The following example usesStart-ThreadJob to create multiple thread jobs to download multiple files at the same time.
$baseUri = 'https://github.com/PowerShell/PowerShell/releases/download'$files = @( @{ Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.msi" OutFile = 'PowerShell-7.3.0-preview.5-win-x64.msi' }, @{ Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.zip" OutFile = 'PowerShell-7.3.0-preview.5-win-x64.zip' }, @{ Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.msi" OutFile = 'PowerShell-7.2.5-win-x64.msi' }, @{ Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.zip" OutFile = 'PowerShell-7.2.5-win-x64.zip' })$jobs = @()foreach ($file in $files) { $jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock { $params = $Using:file Invoke-WebRequest @params }}Write-Host "Downloads started..."Wait-Job -Job $jobsforeach ($job in $jobs) { Receive-Job -Job $job}By default, theInvoke-WebRequest cmdlet validates the values of well-known headers that have astandards-defined value format. The following example shows how this validation can raise anerror and how you can use theSkipHeaderValidation parameter to avoid validating values forendpoints that tolerate invalidly formatted values.
$Uri = 'https://httpbin.org/headers'$InvalidHeaders = @{ 'If-Match' = '12345'}Invoke-WebRequest -Uri $Uri -Headers $InvalidHeadersInvoke-WebRequest -Uri $Uri -Headers $InvalidHeaders -SkipHeaderValidationInvoke-WebRequest: The format of value '12345' is invalid.StatusCode : 200StatusDescription : OKContent : { "headers": { "Host": "httpbin.org", "If-Match": "12345", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.19044; en-US) PowerShell/7.2.5", "X-Amzn-Trace-Id": �RawContent : HTTP/1.1 200 OK Date: Mon, 08 Aug 2022 16:24:24 GMT Connection: keep-alive Server: gunicorn/19.9.0 Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true Content-Type: application�Headers : {[Date, System.String[]], [Connection, System.String[]], [Server, System.String[]], [Access-Control-Allow-Origin, System.String[]]�}Images : {}InputFields : {}Links : {}RawContentLength : 249RelationLink : {}httpbin.org is a service that returns information about web requests andresponses for troubleshooting. The$Uri variable is assigned to the/headers endpoint of theservice, which returns a request's headers as the content in its response.
TheIf-Match request header is defined inRFC-7232 section 3.1 and requires thevalue for that header to be defined with surrounding quotes. The$InvalidHeaders variable isassigned a hash table where the value ofIf-Match is invalid because it's defined as12345instead of"12345".
CallingInvoke-WebRequest with the invalid headers returns an error reporting that the formattedvalue is invalid. The request is not sent to the endpoint.
CallingInvoke-WebRequest with theSkipHeaderValidation parameter ignores the validationfailure and sends the request to the endpoint. Because the endpoint tolerates non-compliant headervalues, the cmdlet returns the response object without error.
This example gets the links in a web page using the HTTP 2.0 protocol. It uses theInvoke-WebRequest cmdlet to get the web page content. Then it uses theLinks property of theBasicHtmlWebResponseObject thatInvoke-WebRequest returns, and theHref property of eachlink.
(Invoke-WebRequest -Uri 'https://aka.ms/pscore6-docs' -HttpVersion 2.0).Links.HrefSome applications, such as Docker, expose a Unix socket for communication. This example queries fora list of Docker images using the Docker API. The cmdlet connects to the Docker daemon using theUnix socket.
Invoke-WebRequest -Uri "http://localhost/v1.40/images/json/" -UnixSocket "/var/run/docker.sock"Allows redirecting from HTTPS to HTTP. By default, any request that is redirected from HTTPS toHTTP results in an error and the request is aborted to prevent unintentionally communicating inplain text over unencrypted connections. To override this behavior at your own risk, use theAllowInsecureRedirect parameter.
This parameter was added in PowerShell 7.4.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Allows sending of credentials and secrets over unencrypted connections. By default, supplyingCredential or anyAuthentication option with aUri that doesn't begin withhttps://results in an error and the request is aborted to prevent unintentionally communicating secrets inplain text over unencrypted connections. To override this behavior at your own risk, supply theAllowUnencryptedAuthentication parameter.
Warning
Using this parameter isn't secure and isn't recommended. It is provided only for compatibilitywith legacy systems that can't provide encrypted connections. Use at your own risk.
This feature was added in PowerShell 6.0.0.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the explicit authentication type to use for the request. The default isNone.TheAuthentication parameter can't be used with theUseDefaultCredentials parameter.
Available Authentication Options:
None: This is the default option whenAuthentication isn't supplied. No explicitauthentication is used.Basic: RequiresCredential. The credentials are sent as an RFC 7617 BasicAuthenticationAuthorization: Basic header in the format ofbase64(user:password).Bearer: Requires theToken parameter. Sends an RFC 6750Authorization: Bearer header withthe supplied token.OAuth: Requires theToken parameter. Sends an RFC 6750Authorization: Bearer header withthe supplied token.SupplyingAuthentication overrides anyAuthorization headers supplied toHeaders orincluded inWebSession.
This feature was added in PowerShell 6.0.0.
| Type: | WebAuthenticationType |
| Default value: | None |
| Accepted values: | None, Basic, Bearer, OAuth |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 toInvoke-WebRequest.
TheBody parameter can be used to specify a list of query parameters or specify the content ofthe response. For query parameters, the cmdlet uses theSystem.Net.WebUtility.UrlEncode methodmethod to encode the key-value pairs. For more information about encoding strings for URLs, seethe UrlEncode() method reference.
When the input is a POST request and the body is aString, the value to the left of the firstequals sign (=) is set as a key in the form data and the remaining text is set as the value. Tospecify multiple keys, use anIDictionary object, such as a hash table, for theBody.
When the input is a GET request and the body is anIDictionary (typically, a hash table), thebody is added to the URI as query parameters. For other request types (such as PATCH), the body isset as the value of the request body in the standardname=value format with the valuesURL-encoded.
When the input is aSystem.Xml.XmlNode object and the XML declaration specifies an encoding,that encoding is used for the data in the request unless overridden by theContentTypeparameter.
TheBody parameter also accepts aSystem.Net.Http.MultipartFormDataContent object. Thisfacilitatesmultipart/form-data requests. When aMultipartFormDataContent object is suppliedforBody, any Content related headers supplied to theContentType,Headers, orWebSession parameters is overridden by the Content headers of theMultipartFormDataContentobject. This feature was added in PowerShell 6.0.0.
| Type: | Object |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | True |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the client certificate that's 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, useGet-PfxCertificate or use theGet-ChildItem cmdlet in the Certificate(Cert:) drive. If the certificate isn't valid or doesn't have sufficient authority, the commandfails.
| Type: | X509Certificate |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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. Certificates can only be mappedonly to local user accounts, not domain accounts.
To see the certificate thumbprint, use theGet-Item orGet-ChildItem command to find thecertificate inCert:\CurrentUser\My.
Note
This feature is only supported on Windows OS platforms.
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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.
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 setConnectionTimeoutSeconds to a valuegreater than zero, but less than 15 seconds, it can take 15 seconds or more before aWebException is thrown, and your request times out.
This parameter replaced theTimeoutSec parameter in PowerShell 7.4. You can useTimeoutSecas an alias forConnectionTimeoutSeconds.
| Type: | Int32 |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Aliases: | TimeoutSec |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the content type of the web request.
If the value forContentType contains the encoding format (ascharset), the cmdlet uses thatformat to encode the body of the web request. If theContentType doesn't specify an encodingformat, the default encoding format is used instead. An example of aContentType with anencoding format istext/plain; charset=iso-8859-5, which specifies theLatin/Cyrillic alphabet.
If you omit the parameter, the content type may be different based on the HTTP method you use:
application/x-www-form-urlencodedapplication/jsonIf you are using theInFile parameter to upload a file, you should set the content type.Usually, the type should beapplication/octet-stream. However, you need to set the content typebased on the requirements of the endpoint.
ContentType is overridden when theBody is aMultipartFormDataContent object.
Starting in PowerShell 7.4, if you use this both this parameter and theHeaders parameter todefine theContent-Type header, the value specified in theContentType parameter is used.
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies a user account that has permission to send the request. The default is the current user.
Type a user name, such asUser01 orDomain01\User01, or enter aPSCredential objectgenerated by theGet-Credential cmdlet.
Credential can be used alone or in conjunction with certainAuthentication parameteroptions. When used alone, it only supplies credentials to the remote server if the remote serversends an authentication challenge request. When used withAuthentication options, thecredentials are explicitly sent.
Credentials are stored in aPSCredentialobject and the password is stored as aSecureString.
Note
For more information aboutSecureString data protection, seeHow secure is SecureString?.
| Type: | PSCredential |
| Default value: | Current user |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies a custom method used for the web request. This can be used if the Request Method requiredby the endpoint isn't an available option on theMethod.Method andCustomMethod can'tbe used together.
This example makes aTEST HTTP request to the API:
Invoke-WebRequest -Uri 'https://api.contoso.com/widget/' -CustomMethod 'TEST'
This feature was added in PowerShell 6.0.0.
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Aliases: | CM |
| Position: | Named |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
| Position: | Named |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates that the cmdlet sets theKeepAlive value in the HTTP header toFalse. By default,KeepAlive isTrue.KeepAlive establishes a persistent connection to the server tofacilitate subsequent requests.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Converts a dictionary to amultipart/form-data submission.Form may not be used withBody.IfContentType is used, it's ignored.
The keys of the dictionary are used as the form field names. By default, form values are convertedto string values.
If the value is aSystem.IO.FileInfo object, then the binary file contents are submitted. Thename of the file is submitted as thefilename property. The MIME type is set asapplication/octet-stream.Get-Item can be used to simplify supplying theSystem.IO.FileInfoobject.
$Form = @{ resume = Get-Item 'C:\Users\jdoe\Documents\John Doe.pdf'}If the value is a collection type, such Arrays or Lists, the for field are submitted multiple times.The values of the list are treated as strings by default. If the value is aSystem.IO.FileInfoobject, then the binary file contents are submitted. Nested collections aren't supported.
$Form = @{ tags = 'Vacation', 'Italy', '2017' pictures = Get-ChildItem 'C:\Users\jdoe\Pictures\2017-Italy\'}In the above example thetags field are supplied three times in the form, once for each ofVacation,Italy, and2017. Thepictures field is also submitted once for each file in the2017-Italy folder. The binary contents of the files in that folder are submitted as the values.
This feature was added in PowerShell 6.1.0.
| Type: | IDictionary |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the headers of the web request. Enter a hash table or dictionary.
Content related headers, such asContent-Type are overridden when aMultipartFormDataContentobject is supplied forBody.
Starting in PowerShell 7.4, if you use this parameter to define theContent-Type header and useContentType parameter, the value specified in theContentType parameter is used.
| Type: | IDictionary |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the HTTP version used for the request. The default is1.1.
Valid values are:
| Type: | Version |
| Default value: | 1.1 |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Gets the content of the web request body from a file. Enter a path and filename. If you omit thepath, the default is the current location.
You also need to set the content type of the request. For example, to upload a file you should setthe content type. Usually, the type should beapplication/octet-stream. However, you need to setthe content type based on the requirements of the endpoint.
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 |
| Default value: | 5 |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies how many times PowerShell retries a connection when a failure code between 400 and 599,inclusive or 304 is received. Also seeRetryIntervalSec parameter for specifying the intervalbetween retries.
| Type: | Int32 |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the method used for the web request. The acceptable values for this parameter are:
DefaultDeleteGetHeadMergeOptionsPatchPostPutTraceTheCustomMethod parameter can be used for Request Methods not listed above.
| Type: | WebRequestMethod |
| Default value: | None |
| Accepted values: | Default, Get, Head, Post, Put, Delete, Trace, Options, Merge, Patch |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates that the cmdlet shouldn't use a proxy to reach the destination. When you need to bypassthe proxy configured in the environment, use this switch. This feature was added in PowerShell6.0.0.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
| Position: | Named |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
This timeout applies to data reads within a stream, not to the stream time as a whole. The defaultvalue, 0, specifies an indefinite timeout.
Setting the value to 30 seconds means that any delay of longer than 30 seconds between data in thestream terminates the request. A large file that takes several minutes to download won't terminateunless the stream stalls for more than 30 seconds.
| Type: | Int32 |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
By default,Invoke-WebRequest returns the results to the pipeline. When you use theOutFileparameter, the results are saved to the specified file and not returned to the pipeline. Enter apath and filename. To send the results to a file and to the pipeline, add thePassThruparameter.
If you omit the path, the default is the current location. The name is treated as a literal path.Names that contain brackets ([]) must be enclosed in single quotes (').
Starting in PowerShell 7.4, you can specify a folder path without the filename. When you do, thecommand uses the filename from the last segment of the resolved URI after any redirections. Whenyou specify a folder path forOutFile, you can't use theResume parameter.
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates that the cmdlet returns the results, in addition to writing them to a file. This parameteris valid only when theOutFile parameter is also used in the command.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates the cmdlet should preserve theAuthorization header, when present, across redirections.
By default, the cmdlet strips theAuthorization 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 |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates the cmdlet should preserve the method of the request across redirections.
By default, the cmdlet changes the method toGET when redirected. Specifying this parameterdisables this logic to ensure that the intended method can be used with redirection.
This feature was added in PowerShell 7.4.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies a proxy server for the request, rather than connecting directly to the internet resource.Enter the URI of a network proxy server.
| Type: | Uri |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies a user account that has permission to use the proxy server specified by theProxyparameter. The default is the current user.
Type a user name, such asUser01 orDomain01\User01, or enter aPSCredential object, such asone generated by theGet-Credential cmdlet.
This parameter is valid only when theProxy parameter is also used in the command. You can't usetheProxyCredential andProxyUseDefaultCredentials parameters in the same command.
| Type: | PSCredential |
| Default value: | Current user |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates that the cmdlet uses the credentials of the current user to access the proxy server thatis specified by theProxy parameter.
This parameter is valid only when theProxy parameter is also used in the command. You can't usetheProxyCredential andProxyUseDefaultCredentials parameters in the same command.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Performs a best effort attempt to resume downloading a partial file.Resume requiresOutFile.
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 attempts 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 complete.
If the local file size is larger than the remote file size, then the local file is overwritten andthe entire remote file is re-downloaded. This behavior is the same as usingOutFile withoutResume.
If the remote server doesn't support download resuming, then the local file is overwritten and theentire remote file is re-downloaded. This behavior is the same as usingOutFile withoutResume.
If the local file doesn't exist, then the local file is created and the entire remote file isdownloaded. This behavior is the same as usingOutFile withoutResume.
This feature was added in PowerShell 6.1.0.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the interval between retries for the connection when a failure code between 400 and 599,inclusive or 304 is received. Also seeMaximumRetryCount parameter for specifying number ofretries. The value must be between1 and[int]::MaxValue.
When the failure code is 429 and the response includes theRetry-After property in its headers,the cmdlet uses that value for the retry interval, even if this parameter is specified.
| Type: | Int32 |
| Default value: | 5 |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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-WebRequest 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.
Before PowerShell 7.4, 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.
Starting in PowerShell 7.4, the web request session is persistent as long as the properties of thesession aren't overridden in a subsequent request. When they are, the cmdlet recreates the sessionwith the new values. The persistent sessions reduce the overhead for repeated requests, making themmuch faster.
To use the web request session in subsequent web requests, specify the session variable in the valueof theWebSession 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 asUserAgent orCredential. Parameter values take precedence over values inthe web request session.
You can't use theSessionVariable andWebSession parameters in the same command.
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Aliases: | SV |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Skips certificate validation checks. This includes all validations such as expiration, revocation,trusted root authority, etc.
Warning
Using this parameter isn't secure and isn't 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 |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates the cmdlet should add headers to the request without validation.
This switch should be used for sites that require header values that don't conform to standards.Specifying this switch disables validation to allow the value to be passed unchecked. Whenspecified, all headers are added without validation.
This switch disables validation for values passed to theContentType,Headers andUserAgent parameters.
This feature was added in PowerShell 6.0.0.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 theSslProtocol parameteras an array of values or as a comma-separated string of those values. The cmdlet combines the valuesusing a binary-OR operation. Passing values as an array is the simplest option and also allows youto use tab-completion on the values. You may not be able to define multiple options on allplatforms.
Note
On non-Windows platforms it may not be possible to supplyTls orTls12 as an option. SupportforTls13 isn't 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 forTls13 was added in PowerShell 7.1.
| Type: | WebSslProtocol |
| Default value: | None |
| Accepted values: | Default, Tls, Tls11, Tls12 |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 aSecureString containing the token. To supply the token manually use thefollowing:
Invoke-WebRequest -Uri $uri -Authentication OAuth -Token (Read-Host -AsSecureString)
This parameter was introduced in PowerShell 6.0.
| Type: | SecureString |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies a value for the transfer-encoding HTTP response header. The acceptable values for thisparameter are:
ChunkedCompressDeflateGZipIdentity| Type: | String |
| Default value: | None |
| Accepted values: | chunked, compress, deflate, gzip, identity |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the name of the Unix socket to connect to. This parameter is supported on Unix-basedsystems and Windows version 1803 and later. For more information about Windows support of Unixsockets, see theWindows/WSL Interop with AF_UNIXblog post.
This parameter was added in PowerShell 7.4.
| Type: | UnixDomainSocketEndPoint |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Specifies the Uniform Resource Identifier (URI) of the internet resource to which the web request issent. Enter a URI. This parameter supports HTTP or HTTPS only.
This parameter is required. The parameter nameUri is optional.
| Type: | Uri |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | 0 |
| Mandatory: | True |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 has noeffect on the operation of the cmdlet.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
Indicates that the cmdlet uses the credentials of the current user to send the web request. Thiscan't be used withAuthentication orCredential and may not be supported on all platforms.
| Type: | SwitchParameter |
| Default value: | False |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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's used by most internet browsers, use theproperties of thePSUserAgent class, suchas Chrome, Firefox, InternetExplorer, Opera, and Safari.
For example, the following command uses the user agent string for Internet Explorer:Invoke-WebRequest -Uri https://website.com/ -UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)
| Type: | String |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | 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 asUserAgent orCredential. Parameter values take precedence over values in the web request session. Contentrelated headers, such asContent-Type, are also be overridden when aMultipartFormDataContentobject is supplied forBody.
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 anInvoke-WebRequest command.Invoke-WebRequest creates thesession and saves it in the variable. In subsequent commands, use the variable as the value of theWebSession parameter.
You can't use theSessionVariable andWebSession parameters in the same command.
| Type: | WebRequestSession |
| Default value: | None |
| Supports wildcards: | False |
| DontShow: | False |
| Position: | Named |
| Mandatory: | False |
| Value from pipeline: | False |
| Value from pipeline by property name: | False |
| Value from remaining arguments: | False |
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable,-InformationAction, -InformationVariable, -OutBuffer, -OutVariable, -PipelineVariable,-ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, seeabout_CommonParameters.
You can pipe the body of a web request to this cmdlet.
This cmdlet returns the response object representing the result of the web request.
PowerShell includes the following aliases forInvoke-WebRequest:
iwrBeginning with PowerShell 6.0.0Invoke-WebRequest supports basic parsing only.
For more information, seeBasicHtmlWebResponseObject.
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 determined by your platform:
The environment variables used forDefaultProxy 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 aren't defined.NO_PROXY: a comma-separated list of hostnames that should be excluded from proxying.PowerShell 7.4 added support for the Brotli compression algorithm.
Was this page helpful?
Need help with this topic?
Want to try using Ask Learn to clarify or guide you through this topic?
Was this page helpful?
Want to try using Ask Learn to clarify or guide you through this topic?