PowerShell -- Invoke-RestMethod: ”内置“在Shell中的cURL
Eric - http://www.discoposse.com/
PowerShell 3.0里很棒的一个Cmdlet就是Invoke-RestMethod。有了这个命令,我们在PowerShell Script中就能直接使用HTTP方法来访问网络资源,这些HTTP方法包括Get, Head, Post, Put, Delete, Trace, Options, Merge, Patch. 过去如果你想在PowerShell里做同样的事,一般只能选择一个为Cmd写的命令行工具cURL(Linux里常用的是Wget), 你可以在你的batch脚本或者PowerShell脚本里使用cURL来获取你需要的HTTP资源。当然,cURL很胜任这项工作,不过既然PowerShell 3.0里内置了有同样功能的Invoke-RestMethod, 那么就让我们看看它用起来怎么样吧。
假设我们要从一个网站上获取些XML数据并保存到一个文件中,那么使用cURL的话就是下面这行命令:
curl.exe www.discoposse.com/index.php/feed > C:\Temp\DiscoPosseFeed.xml
这并不是件复杂的操作,cURL完全可以胜任,但是有个问题,curl是个第三方命令行工具,也就是说上面这行命令的可移植性不好,毕竟不是每台电脑上都装有cURL。Invoke-RestMethod不一样,PowerShell 3.0是内嵌在Windows 8/Windows Server 2012里的,只要有PowerShell 3.0,就有Invoke-RestMethod这个内置命令。使用Invoke-RestMethod的话,我们需要下面这行命令:
Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -Method Get
很简单吧,Invoke-RestMethod的参数名和使用语法都会让这行命令更容易被人理解 -- 使用HTTP Get方法来获取指定URI的news feed。Invoke-RestMethod使用的默认方法就是Get,所以我们这个例子里也可以干脆省略"-Method Get"。
现在我们来看看这个命令会返回什么东西:
PS C:\Users> Invoke-RestMethod -Uri www.discoposse.com/index.php/feed -Method Get title : Linked Mode separation? Veeam to the Rescue link : http://www.discoposse.com/index.php/2012/07/31/linked-mode-separation-veeam-to-the-rescue/ comments : {http://www.discoposse.com/index.php/2012/07/31/linked-mode-separation-veeam-to-the-r