Invoke-WebRequest с прокси
| Время чтения: 11 минут |
В конце этого руководства по прокси в Invoke-WebRequest PowerShell вы узнаете:
- Как использовать Invoke-WebRequest с прокси в PowerShell
- Как выполнять HTTP-запросы, загружать файлы, разбирать веб-страницы с помощью PowerShell
Давайте приступим!
Основы использования Invoke-WebRequest
Команда Invoke-WebRequest может использоваться для запроса ресурсов HTTP/HTTPS/FTP непосредственно из консоли PowerShell. Эту команду можно использовать для отправки HTTP-запросов (GET и POST), загрузки файлов с веб-сайта, разбора HTML веб-страниц, аутентификации, заполнения и отправки веб-форм и многое другое. В этой статье мы рассмотрим основные примеры использования командлета Invoke-WebRequest в PowerShell для взаимодействия с веб-сервисами.

Фото: Patrick Tomasso на Unsplash
Представьте, что вам нужно проверить ответ API в интеграционном тесте. Ответ API – это мастер-данные в формате JSON, статичные, но достаточно обширные, и единственным источником правды, с которым вы можете сравнить данные, является таблица на веб-сайте вашего любимого вики-программного обеспечения (например, wikipedia.com или страница Confluence). Идея заключается в том, чтобы разобрать таблицу с помощью Powershell и сравнить ее с JSON-ответом вызова API.
Вкратце, API описывается как таблица на странице Confluence, и ваша задача – понять смысл ячеек таблицы и разобрать их, чтобы Powershell мог обработать этот большой объем данных. Звучит увлекательно, не так ли?
Предпосылки для начала работы с прокси в PowerShell
Прокси действует как посредник между клиентом и сервером назначения. Он перехватывает ваши запросы, пересылает их на сервер, получает ответы от сервера и отправляет их обратно вам. Таким образом, сервер назначения увидит запросы как отдельные от IP и местоположения выбранного прокси-сервера, а не от вас.
Для начала использования прокси в PowerShell с Invoke-WebRequest необходимо понимать, как выглядит URL прокси-сервера.
Вот URL прокси для использования в PowerShell Invoke-WebRequest:
<ПРОТОКОЛ>://[<ИМЯ_ПОЛЬЗОВАТЕЛЯ>:<ПАРОЛЬ>]@<ХОСТ>[:<ПОРТ>]Это состоит из:
- <ПРОТОКОЛ>: Протокол для подключения к прокси-серверу.
- <ХОСТ>: IP-адрес или URL имени хоста прокси-сервера.
- <ПОРТ>: Номер порта, на котором прокси-сервер слушает.
- <ИМЯ_ПОЛЬЗОВАТЕЛЯ>: Опциональное имя пользователя для указания при требуется аутентификация прокси.
- <ПАРОЛЬ>: Опциональный пароль для указания при требуется аутентификация прокси.
Invoke-WebRequest: Эта операция не поддерживается для относительного URI.Что касается протоколов прокси, наиболее популярными являются HTTP, HTTPS и SOCKS. В PowerShell 5.1 Invoke-WebRequest поддерживает только HTTP, тогда как в PowerShell 7.x он также поддерживает HTTPS и SOCKS.
Пора получить действующий HTTP-прокси! Можно найти его бесплатно онлайн, как показано ниже:
Протокол: HTTP; IP-адрес: 190.6.23.219; Порт: 999http://190.6.23.219:999Предупреждение
Пользование бесплатными прокси-серверами допустимо для обучающих целей, но вы не можете полагаться на них в реальных сценариях. Бесплатные прокси-сервера ненадежны, подвержены ошибкам, медленны, требовательны к данным и имеют короткий срок службы. Не используйте их!
Решение? Премиальные прокси от Bright Data, лучшего провайдера на рынке. Подпишитесь и попробуйте наши надежные прокси бесплатно.
http://admin-4521:@rUuH3tJqf45.103.203.109:9571$request = Invoke-WebRequest -Uri https://........ `
$requestEncode = $request.ParsedHtml.documentElement.innerHtml
$requestEncodeкоторый возвращает:
// Переключить видимое состояние элементов
function replaceHeroContentWithResults() { const results = document.querySelector(.hero__results); const heroContent = document.querySelector(.hero__content); results.classList.toggle(is-hidden); heroContent.classList.toggle(is-hidden);
}
// Показать результаты поиска
function renderResultsPartial() { const results = document.querySelector(.hero__results); results.innerHTML = <SECTION class=results dark-theme?>\n <HEADER class=results__header>\n <H2 class=results__title>Search Results</h2>\n <DIV class=results__nav>\n <P class=results__subtitle>Your search contained one ingredient known to promote the growth of malassezia.</p>\n </div>\n </header>\n\n <TABLE class=results__table>\n <TBODY>\n <TR>\n <TH scope=col>ingredient name</th>\n <TH scope=col>category</th>\n </tr>\n\n <TR>\n <TH scope=row data-label=name>\n <SPAN class=type-of lipids?>\n olea europaea (olive) fruit oil\n </span>\n </th>\n </span><TD data-label=category>\n <SPAN class=type-of lipids?>\n Lipids\n </span>\n </td>\n </tr>\n </tbody>\n </table>\n\n <SECTION class=results__comments>\n </section>\n\n <SECTION class=results__footer>\n <A href=/search-again data-remote=true>Search again</a>\n </section>\n</section>\n;
}
// Сбросить форму поиска
function resetSearchForm() { const search = document.querySelector(.jsSearchForm); search.reset();
}
replaceHeroContentWithResults();
resetSearchForm();
renderResultsPartial();
</a></span></tr></tbody></p></div></h2>Не разобран, поскольку он не работает, когда я добавляю -UseBasicParsing, мой вопрос заключается в том, как выбрать элемент из этого HTML, например, название ингредиента
Разбор и извлечение HTML-содержимого веб-страницы с помощью PowerShell
Команда Invoke-WebRequest позволяет быстро и удобно обрабатывать содержимое любой веб-страницы. При обработке HTML-страницы создаются коллекции ссылок, веб-форм, изображений, скриптов и т. д.
Давайте посмотрим, как получать доступ к конкретным объектам на веб-странице. Например, я хочу получить список всех исходящих ссылок (объектов A HREF) на целевой HTML-странице:
Создание коллекции ссылок с помощью Invoke-WebRequest

Вы можете выбирать только ссылки с определенным CSS классом:
Или определенный текст в адресе URL:

Затем отобразите список всех изображений на этой странице:
Создайте коллекцию полных URL-адресов к этим изображениям:
Инициализируйте новый экземпляр класса WebClient:
$wc = New-Object System.Net.WebClientЗагрузите все файлы изображений со страницы (с их оригинальными именами файлов) в папку c:\\too1s\\:

Установка
Для демонстрации того, как разбирать таблицу HTML с помощью Powershell, я создал репозиторий GitHub: ms_powershellTableCoverter.
Чтобы иметь рабочий пример, вы найдете файл Dockerfile в каталоге docker, который запускает сервер nginx с статическим файлом index.html, содержащим таблицу с фиктивной спецификацией для API. Вот команды для запуска веб-сервера:
cd docker
docker build -t nginxwebsrvstatictable:0.0.1 .
docker run -p 8080:80 nginxwebsrvstatictable:0.0.1Если эти две команды успешны, мы можем продолжить с разбором таблицы с помощью Powershell.
Какой прокси PowerShell следует использовать?
Ответ на этот вопрос меняется в зависимости от того, что вы хотите достичь с помощью вашего запроса Invoke-WebRequest. Чтобы найти подходящий прокси PowerShell для ваших потребностей, рассмотрите различные типы доступных прокси:
Прокси серверов данных: Они быстрые и дешевые, но могут быть легко обнаружены и заблокированы сайтами из-за их идентифицируемых диапазонов IP.
Жилые прокси: Они предлагают вращающиеся настоящие IP-адреса с реальных устройств в конкретных местах. Это означает, что они могут гарантировать высокий уровень анонимности. Жилые прокси идеально подходят для доступа к сайтам, которые полагаются на блокировки географического ограничения или для избежания анти-бот мер.
Прокси провайдеров Интернет-провайдеров: Они надежные, быстрые и очень надежные, так как предоставляют статические IP-адреса с устройств, зарегистрированных у поставщиков услуг Интернета. Прокси провайдеров Интернет-провайдеров также называются жилыми статическими прокси и являются идеальным решением для мониторинга SEO и исследований рынка.
Мобильные прокси: Они предоставляют IP-адреса настоящих мобильных устройств для высокого уровня анонимности. Они полезны для доступа к приложениям, сайтам или контенту, специально разработанным для мобильных устройств.
Как загрузить файл по HTTP/FTP с помощью PowerShell Wget (Invoke-WebRequest)?
wget https://download-installer.cdn.mozilla.net/pub/firefox/releases/102.0.1/win64/en-US/Firefox%20Setup%20102.0.1.exe -outfile “c:\tools\firefox_setup.exe”
Эта команда загрузит файл с HTTP сайта и сохранит его в указанной директории.
Вы можете узнать размер файла в MB до его загрузки с помощью wget:
$url = https://download-installer.cdn.mozilla.net/pub/firefox/releases/102.0.1/win64/en-US/Firefox%20Setup%20102.0.1.exe
(Invoke-WebRequest $url -Method Head).Headers.Content-Length/1Mb
Ниже приведен пример сценария PowerShell, который найдет все ссылки на файлы *.pdf на целевой веб-странице и массово загрузит все найденные файлы с веб-сайта на ваш компьютер (каждый файл pdf сохраняется под случайным именем):
По результатам выполнения сценария в целевом каталоге будут загружены все файлы PDF с этой страницы. Каждый файл сохраняется под случайным именем.
В современном PowerShell Core (версии 6.1 и новее) cmdlet Invoke-WebRequest поддерживает режим возобновления. Обновите версию PowerShell Core и вы сможете использовать параметр -Resume для команды Invoke-WebRequest, чтобы автоматически возобновлять загрузку файла в случае недоступности канала связи или сервера:
Invoke-WebRequest -Uri $Uri -OutFile $OutFile –ResumeИспользование Invoke-WebRequest с аутентификацией
Некоторые веб-ресурсы требуют аутентификации для доступа. Вы можете использовать различные типы аутентификации с cmdlet Invoke-WebRequest (Basic, NTLM, Kerberos, OAuth или сертификатная аутентификация).
$cred = Get-Credential
wget -Uri https://somesite.com -Credential $credInvoke-WebRequest https://somesite.com -UseDefaultCredentialsАвторизация с помощью сертификата требует указания его отпечатка:
Invoke-WebRequest https://somesite.com -CertificateThumbprint xxxxxxxxxxxxxxxxxxxxxxxxxxxxxВы можете использовать современную аутентификацию Bearer/OAuth токенов в ваших сценариях PowerShell.
Сначала вам нужно получить токен OAuth от вашего поставщика REST API (вне рамок этого сообщения);
Преобразуйте токен с помощью cmdlet ConvertTo-SecureString:
$Token = 12345678912345678901234567890 | ConvertTo-SecureString -AsPlainText –ForceТеперь вы можете выполнить аутентификацию OAuth:
$Params = @{
Uri = https://somesite.com
Authentication = Bearer
Token = $Token }
Invoke-RestMethod @ParamsКак указать HTTP-прокси в Invoke-WebRequest
Прежде чем начать, выполните следующую команду в PowerShell:
Invoke-WebRequest https://httpbin.org/ipЭто должно вывести что-то вроде:
StatusCode : 200
StatusDescription : OK
Content : {
origin: 194.34.233.12
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 32
Content-Type: application/json
Date: Thu, 01 Feb 2024 10:46:14 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials, ```
true], [Content-Length, 32]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 32Focus on the Content field. That will contain your IP.
Why? Because the /ip endpoint from the HTTPBin project returns the origin IP of the request. In other words, it returns the IP address of the machine that performed the request. In this case, that is your machine’s IP.
If you want to access only the Content field, you can do it with:
$response = Invoke-WebRequest "https://httpbin.org/ip"
$response.Content
This would print:
{
"origin": "194.34.233.12"
}If you route that request through a proxy, you should see the IP address of the proxy server and not yours. Calling that endpoint is therefore a good test to verify that the specified PowerShell Invoke-WebRequest proxy is working as expected.
There are a couple of ways to set a PowerShell proxy in Invoke-WebRequest. Find out more in the step-by-step guided sections below!
Using a Command Line Option
Invoke-WebRequest offers the -Proxy flag to specify a proxy URL for your request.
So, the syntax to use Invoke-WebRequest with a proxy server becomes:
Invoke-WebRequest -Proxy "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]" <Uri>If you now execute this PowerShell command:
Invoke-WebRequest -Proxy "http://190.6.23.219:999" "https://httpbin.org/ip"
Invoke-WebRequest -Uri "http://httpbin.org/ip" -Proxy "http://brd.superproxy.io:22225" -ProxyCredential (New-Object System.Management.Automation.PSCredential("brd-customer-CUSTOMER_ID-zone-ZONE’S_NAME", ("ZONE’S_PASSWORD" | ConvertTo-SecureString -AsPlainText -Force)))
The result should be:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "190.6.23.219"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 31
Content-Type: application/json
Date: Thu, 01 Feb 2024 12:36:56 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 31]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 31Notice that the origin in Content matches the proxy server IP. This proves that the target server sees the request as coming from the proxy, as expected. Awesome!
Note: Do not forget that free proxies are short-lived! By the time you read this guide, it is unlikely that the above server is still alive. In case of an error, replace it with a fresh proxy.
Using Environment Variables
Since PowerShell 7.0, Invoke-WebRequest supports proxy configuration via environment variables.
HTTP_PROXY:The URL of the proxy server to use in case of HTTP requests.
HTTPS_PROXY: The URL of the proxy server to use in case of HTTPS requests.
On Windows, you can set the two environment variables with this PowerShell syntax:
$env:HTTP_PROXY = "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"
$env:HTTPS_PROXY = "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"In our example, the commands will become:
$env:HTTP_PROXY = "http://190.6.23.219:999"
$env:HTTPS_PROXY = "http://190.6.23.219:999"On macOS and Linux, you need to use the syntax below:
export HTTP_PROXY="<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"
export HTTPS_PROXY="<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]"So, the two commands will be:
export http_proxy="http://190.6.23.219:999"
export https_proxy="http://190.6.23.219:999"From now on, every Invoke-WebRequest request will go through the specified proxies without having to add the -Proxy option. After setting the envs, launch the command below:
Invoke-WebRequest "https://httpbin.org/ip"
You will get the same result as before:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "190.6.23.219"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 31
Content-Type: application/json
Date: Thu, 01 Feb 2024 12:36:56 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 31]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 31To turn off the Invoke-WebRequest proxies, unset the environment variables with:
$env:HTTP_PROXY = ""
$env:HTTPS_PROXY = ""
Or on macOS and Linux:
unset HTTP_PROXY
unset HTTPS_PROXYInvoke-WebRequest will go back to its standard behavior, and https://httpbin.org/ip will now expose your IP.
How To Use HTTPS and SOCKS Proxies in PowerShell
If you need to use an HTTPS or SOCKS proxy, you must upgrade to version 7.x+ of PowerShell. Otherwise, Invoke-WebRequest will fail with:
**Invoke-WebRequest** : The ServicePointManager does not support proxies with the https scheme.
Or in the case of a SOCKS proxy:
**Invoke-WebRequest** : The ServicePointManager does not support proxies with the socks scheme.
When dealing with HTTPS or SOCKS proxies in PowerShell 7.x, the Invoke-WebRequest command structure remains the same:
Invoke-WebRequest -Proxy "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]" <Uri>What changes is that <PROTOCOL> will be https, socks4, socks4a, socks5, or socks5a, instead of http.
If you try to invoke a request with a proxy involving a protocol other than those mentioned above, you will get this error:
Invoke-WebRequest: Only the 'http', 'https', 'socks4', 'socks4a' and 'socks5' schemes are allowed for proxies.Thus, a complete example of an Invoke-WebRequest SOCKS proxy request is:
Invoke-WebRequest -Proxy "socks5://94.14.109.54:3567" "http://httpbin.org/ip"
As you can expect, the result will be:
StatusCode : 200
StatusDescription : OK
Content : {
"origin": "94.14.109.54"
}
RawContent : HTTP/1.1 200 OK
Connection: keep-alive
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Content-Length: 31
Content-Type: application/json
Date: Thu, 01 Feb 2024 12:47:56 GMT...
Forms : {}
Headers : {[Connection, keep-alive], [Access-Control-Allow-Origin, *], [Access-Control-Allow-Credentials,
true], [Content-Length, 31]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 31How to Fill and Submit HTML Form with PowerShell?
Using the next command, display the list of the fields to fill in the login HTML form (login_form):
Assign the desired values to all fields:
To submit (sent) the filled form to the server, call the action attribute of the HTML form:
You can also use the JSON format to send data to a web page with the POST method:
Prerequisites
Install-Module -Name PowerHTML
After a few moments, the package should be available on your system. You can test it if you type “ConvertFrom-HTML” and hit enter. If no errors are displayed, the installation procedure was successful.
Parse the HTML document
First things first, we need to parse the entire HTML web page with this command:
We assume, that there is only one table on the page respectively the data is stored in the first table of the page. Hence, we can get the table headers with this command
Next, we initialize the array, where the table’s data will be stored.
Afterward, when everything is set and initialized correctly, we can start grabbing the data from the table:
The main part of the script counts the table’s rows, excluding the header row. Then it starts a loop, beginning at row two, right after the table’s header. The script fetches the cells of a particular row into an array and creates a new empty hash for it. Now with the cells in place, it loops over the table’s header and sets a key for every header column with the associated value of the table row. Last, it “returns” the hash back from the loop to the pwshTable variable.
Now, when calling pwshTable on the command prompt, you may see something like this:
Quite handy and efficient!
Hence, the call to Invoke-RestMethod returns an object, which contains an array “catbreeds”, which contains information about cat breeds. The rest of the comparison is quite easy:
For each entry in the array pwshTable, get the object, where the breed matches the property “Breed”. Write to the console, if the breed was found or not.
Thats it! Now, with the output of the console, you can easily observe, if the static response of the API and the content of the table match!
Please comment on your thoughts on the article. I’m curious what you guys think about it and if it could be useful.
Get Web Page Content with Invoke-WebRequest Cmdlet
The Invoke-WebRequest PowerShell cmdlet allows you to send the HTTP, HTTPS, or FTP request with the GET method to the specified web page and receive a response from the server.
There are two aliases for the Invoke-WebRequest command in Windows: iwk and wget.
Invoke-WebRequest -Uri "https://woshub.com"

Tip. If you are connected to the Internet via a proxy server, you must properly configure PowerShell to access the Web through the proxy server. If you do not set proxy parameters, you will receive an error when you run the IWK command:
Invoke-WebRequest: Unable to connect to the remote server
CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

The command loaded the page and displayed its contents in the PowerShell console. The returned response is not just the HTML code of the page. The Invoke-WebRequest cmdlet returns an object of type _HtmlWebResponseObjec_t. Such an object is a collection of forms, links, images, and other important elements of an HTML document. Let’s look at all the properties of this object:

To get the raw HTML code of the web page that is contained in the _HtmlWebResponseObjec_t object, run:
You can list the HTML code along with the HTTP headers returned by the web server:

You can check only the web server HTTP status code and the HTTP headers of the HTML page:
As you can see, the server has returned a response 200. This means that the request has been successful, and the web server is available and works correctly.
Key Value
— —–
Transfer-Encoding chunked
Connection keep-alive
Vary Accept-Encoding,Cookie
Cache-Control max-age=3, must-revalidate
Content-Type text/html; charset=UTF-8
Date Wed, 13 Jul 2022 02:28:32 GMT
Server nginx/1.20.2
X-Powered-By PHP/5.6.40
To get the last modification time of a web page:

The list of available agents in PowerShell can be displayed like this:
Tips and Tricks You Need to Know
See some useful tricks and valuable tips for dealing with a PowerShell Invoke-WebRequest proxy like a pro.
Ignore the PowerShell Proxy Configuration
Invoke-WebRequest -NoProxy <Uri>
This instructs Invoke-WebRequest to contact <Uri> without using a proxy.
To verify that this approach works, set up a proxy in the envs and run:
Invoke-WebRequest -NoProxy "https://httpbin.org/ip"The resulting origin will contain your IP, not that of the proxy server.
Avoid SSL Certificate ErrorsWhen using HTTP proxies, your requests may fail because of SSL certificate errors. To avoid that, specify the -SkipCertificateCheck option:
Invoke-WebRequest -SkipCertificateCheck -Proxy "<PROTOCOL>://[<USERNAME>:<PASSWORD>]@<HOST>[:<PORT>]" <Uri>-SkipCertificateCheck helps you avoid certificate errors by allowing insecure server connections. Keep in mind that using this parameter is not secure. Set it only when dealing with known hosts.
For example, you can contact HTTPBin through a proxy while bypassing SSL issues with:
Invoke-WebRequest -SkipCertificateCheck -Proxy "http://190.6.23.219:999" "https://httpbin.org/ip"What Is PowerShell Invoke-WebRequest?
Invoke-WebRequest is a PowerShell cmdlet for sending HTTP, HTTPS, and FTP requests to web servers and web services. By default, it automatically parses the response produced by the server and returns collections of forms, links, images, or other significant HTML elements.
Usually, it is used for accessing REST APIs, downloading files from the web, or interacting with web services. This is the basic syntax of an Invoke-WebRequest request:
Invoke-WebRequest [-Uri] <Uri> [-Method <WebRequestMethod>] [-Headers <IDictionary>] [-Body <Object>]The key parameters to remember are:
-Uri: The URI of the web resource to which the request is sent.
-Method: The HTTP method to use for the request (e.g., GET, POST, PUT, DELETE). Invoke-WebRequest sends GET requests by default.
-Headers: The additional HTTP headers to include in the request.
-Body: The body of the request to send to the server.
As you can see, the only required argument is <Uri>. Thus, in short, the simplest syntax to perform a GET request to a given URI is:
Invoke-WebRequest <Uri>This cmdlet was introduced in PowerShell 3.0, in 2012.
Installing Invoke-WebRequest
To use Invoke-WebRequest, you need PowerShell. So, let’s learn how to install PowerShell and get access to the Invoke-WebRequest cmlet!
Windows
You can verify the current version of PowerShell installed on your Windows machine with this command:
$PSVersionTableOn PowerShell 7.x, that should print something similar to:
PSVersion 7.4.1
PSEdition Core
GitCommitId 7.4.1
OS Microsoft Windows 10.0.22631
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0macOS and Linux
Ignore SSL/TLS Certificate Checks
Another issue is that the Invoke-WebRequest cmdlet is closely related to Internet Explorer. For example, in Windows Server Core editions in which IE is not installed (or removed), the Invoke-WebRequest cmdlet cannot be used.
Invoke-WebRequest: The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer’s first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.
In this case, the WebClient class can be used instead of Invoke-WebRequest. For example, to download a file from a specified URL, use the command.
(New-Object -TypeName 'System.Net.WebClient').DownloadFile($Url, $FileName)
If an invalid SSL certificate is used on an HTTPS site, or PowerShell doesn’t support this type of SSL/TLS protocol, then the Invoke-WebRequest cmdlet drops the connection.
Invoke-WebRequest : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Invoke-WebRequest : The request was aborted: Could not create SSL/TLS secure channel.

By default, Windows PowerShell (in early builds of Windows 10, Windows Server 2016, and older versions of Windows) uses the legacy and insecure TLS 1.0 protocol for connections (check the blog post describing the PowerShell module installation error: Install-Module: Unable to download from URI).
In PowerShell Core, the Invoke-WebRequest cmdlet has an additional parameter –SkipCertificateCheck that allows you to ignore invalid SSL/TLS certificates.
Another significant drawback of the Invoke-WebRequest cmdlet is its rather low performance. When downloading a file, the HTTP stream is entirely buffered into memory, and only after the full download is completed is saved to disk. Thus, when downloading large files using Invoke-WebReques, you may run out of RAM.
Conclusion
In this PowerShell proxy guide, you learned what Invoke-WebRequest is, how it works, and how to use it with an HTTP/HTTPS/SOCKS proxy. As it turned out, you cannot rely on proxies from free providers. Therefore, the only decision to be made is which proxy provider you should adopt. Save time and energy and go directly for the best on the market, Bright Data.
Bright Data controls the best proxy servers in the world, serving Fortune 500 companies and over 20,000 customers. Its worldwide proxy network involves:
Overall, that is one of the largest and most reliable scraping-oriented proxy networks on the market.



