S
S
SMARTi2015-12-28 12:15:55
PowerShell
SMARTi, 2015-12-28 12:15:55

How to handle exceptions on Invoke-WebRequest to get Http StatusCode?

When called

Invoke-WebRequest localhost
a normal response will return, which will contain the StatusCode of interest to me.
StatusCode : 200
StatusDescription : OK

But if you call a site that returns a 401 status, in my case it is a site with Windows Authorization, an exception will occur, although for me this is normal and I just want to know the status.
Invoke-WebRequest : ������ ��������
401 - ������ ��������. ������������ ���������������� ������ ������.
��������������� ������ ������ �� ���� ����� �� �������� � ���� �������� ���� ��������.
string:1 character:1
+ Invoke-WebRequest 192.168.3.5:10000
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

How to handle this correctly to get the current status 401.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
azarij, 2015-12-28
@azarij

after an error is received, it will be the first one in $Error. find it and request .exception or .exception.response:
($error | select -first 1).exception
($error | select -first 1).exception.response

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question