如何获取数字HTTP状态codeS在PowerShell中状态、数字、PowerShell、HTTP

2023-09-02 23:53:44 作者:奶嘴好甜

我知道几个不错的方式建立在PowerShell中的Web客户端:.NET类System.Net.WebClient和System.Net.HttpWebRequest,或COM对象MSXML2.XMLHTTP。从我可以告诉,唯一一个允许您访问的数字状态code(例如200,404),是最后一个,COM对象。我的问题是,我不喜欢这样的工作方式,我不喜欢依靠在那里COM对象上。我也知道,不时微软将决定杀死COM对象(Ac​​tiveX消除位),由于安全漏洞等。

I know of a few good ways to build web clients in PowerShell: the .NET classes System.Net.WebClient and System.Net.HttpWebRequest, or the COM object Msxml2.XMLHTTP. From what I can tell, the only one which gives you access to the numeric status code (e.g. 200, 404), is the last, the COM object. The problem I have is that I don't like the way it works and I don't like relying on the COM object being there. I also know that from time to time Microsoft will decide to kill COM objects (ActiveX kill bits) due to security vulnerabilities and so on.

难道还有其他的.NET方法我失踪?是状态code在这另外两个对象之一,我只是不知道如何得到它?

Is there another .NET method I'm missing? Is the status code in one of these other two objects and I just don't know how to get at it?

推荐答案

同时使用x0n和约书亚壶的答案,风水轮流转了code的例子,我希望这不是太糟糕的形式:

Using both x0n and joshua ewer's answers to come full circle with a code example, I hope that's not too bad form:

PS > $url = 'http://google.com'
PS > $req = [system.Net.WebRequest]::Create($url)
PS > try {
       $res = $req.GetResponse()
     } catch [System.Net.WebException] {
       $res = $_.Exception.Response
     }
PS > $res.StatusCode
OK
PS > [int]$res.StatusCode
200