PowerShell利用Curl發(fā)送請求

前言

PowerShell能干什么呢?PowerShell首先是個Shell,定義好了一堆命令與操作系統(tǒng),特別是與文件系統(tǒng)交互,能夠啟動應用程序,甚至操縱應用程序;第二,PowerShell允許將幾個命令組合起來放到文件里執(zhí)行,實現(xiàn)文件級的重用,也就是說有腳本的性質(zhì);第三,PowerShell能夠能夠充分利用.Net類型和COM對象,來簡單地與各種系統(tǒng)交互,完成各種復雜的、自動化的操作。

當我們習慣了windows的界面模式就很難轉(zhuǎn)去命令行,甚至以命令行發(fā)家的git也涌現(xiàn)出各種界面tool。然而命令行真的會比界面快的多,如果你是一個碼農(nóng)。

需求

接到需求分析bug,需要訪問http。那臺機器屬于product,不允許裝postman。我只能手動命令行來發(fā)請求。發(fā)現(xiàn)了內(nèi)置的PowerShell中有curl命令。試了半天,總是命令不對,google發(fā)現(xiàn)這個curl是冒名頂替的,只是一個Invoke-WebRequest的alias。參考

PS C:\Users\wweim> get-alias -definition invoke-webrequest | format-table -autosize

CommandType Name                      Version Source
----------- ----                      ------- ------
Alias       curl -> Invoke-WebRequest
Alias       iwr -> Invoke-WebRequest
Alias       wget -> Invoke-WebRequest

powershell中使用curl

獲取幫助:
get-help invoke-webrequest 或者 get-help invoke-webrequest -online
online參數(shù)會打開官方文檔powershell

PS C:\Users\wweim> get-help invoke-webrequest

名稱
    Invoke-WebRequest

語法
    Invoke-WebRequest [-Uri] <uri>  [<CommonParameters>]


別名
    iwr
    wget
    curl


備注
    Get-Help 在此計算機上找不到該 cmdlet 的幫助文件。它僅顯示部分幫助。
        -- 若要下載并安裝包含此 cmdlet 的模塊的幫助文件,請使用 Update-Help。
        -- 若要聯(lián)機查看此 cmdlet 的幫助主題,請鍵入: "Get-Help Invoke-WebRequest -Online" 或
           轉(zhuǎn)到 https://go.microsoft.com/fwlink/?LinkID=217035。

可以看到curl也是別名,linux的wget也在其中,這樣為習慣其他平臺的用戶提供了方便,但是用法上也稍有區(qū)別
基本用法介紹:

#請求地址
- Uri $uri
#添加header
-Headers @{"content-type"="application/json";"authorization"="bearer token"}
#指定Method
-Method Get
#將獲取到的content輸出到文件
-OutFile 'c:\Users\rmiao\temp\content.txt'
  • get 請求
PS C:\Users\wweim> $R = Invoke-WebRequest -URI http://www.bing.com?q=how+many+feet+in+a+mile

查看返回結(jié)果

PS C:\Users\wweim> $R
StatusCode        : 200
StatusDescription : OK
Content           : <!DOCTYPE html><html lang="zh" xml:lang="zh" 
RawContent        : HTTP/1.1 200 OK
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 118264
...... # 省略n多字符

內(nèi)容篩選

PS C:\Users\wweim> $R.AllElements | where {$_.innerhtml -like "*=*"} | Sort { $_.InnerHtml.Length } | Select InnerText

返回結(jié)果

innerText
---------
下一頁
....#省略n多字符
  • post請求
$uri = 'https://www.pstips.net/restapi/v2'
 
$hash = @{ name = "$name";
           pwd = "$passwd";
        }
$headers = @{"accept"="application/json"}
$JSON = $hash | convertto-json
curl -uri $uri -Method POST -Body $JSON

示例:

PS C:\Users\wweim> $uri = "http://localhost:8001/api/Account/login"
PS C:\Users\wweim> $header = @{"content-type"="application/json"}
PS C:\Users\wweim> $hash = @{userName='bz';password='1';}
PS C:\Users\wweim> $json = $hash | convertto-json
PS C:\Users\wweim> curl -h $header -uri $uri -method post -body $json

得到如下內(nèi)容

PS C:\Users\wweim> curl -h $header -uri $uri -method post -body $json

StatusCode        : 200
StatusDescription : OK
Content           : {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi6YOo6ZW_IiwiaHR0cDovL3NjaGVtYXMueG1s
                    c29hcC5vcmcvd3MvMjAwNS8wNS9pZGVud...
RawContent        : HTTP/1.1 200 OK
                    Transfer-Encoding: chunked
                    Connection: keep-alive
                    Content-Type: application/json; charset=utf-8
                    Date: Thu, 16 Jan 2020 02:15:32 GMT
                    Server: nginx/1.14.0 (Ubuntu)

                    {"token":"eyJh...
Forms             : {}
Headers           : {[Transfer-Encoding, chunked], [Connection, keep-alive], [Content-Type, application/json; charset=utf-8], [Date, Thu, 16 Jan 2020 02:15:32 GMT]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 1818

會發(fā)現(xiàn)content內(nèi)容被截斷了,想要獲取完整的content,可加參數(shù)| Select -ExpandProperty Content

PS C:\Users\wweim> curl -h $header -uri $uri -method post -body $json | select -expandproperty content
{"token":"XJ5Z3JvdXBz","userInfo":{"id":"08ef7b95-c4aa-4006-a074-66eaf0ff1974","companyId":"77a95763-3c6e-4296-8fd6-14d62316d535","roleId":"28b0acf3-76b0-4965-95cb-da2f5bc63bc2","creationTime":"0001-01-01 00:00:00","creatorId":"00000000-0000-0000-0000-000000000000","lastModificationTime":"0001-01-01 00:00:00","lastModifierId":"00000000-0000-0000-0000-000000000000","isDeleted":false,"userName":"部 長","gender":1,"dateOfBirth":"0001-01-01 00:00:00","email":"","phoneNumber":"132231121","avatarUrl":"","state":1,"publicOpenId":null,"miniOpenId":null},"companyInfo":{"id":"77a95763-3c6e-4296-8fd6-14d62316d535","name":"1jcsgs","shortName":"分局","introduction":"分局","level":1,"parentId":"00000000-0000-0000-0000-000000000000","state":1,"baiduX":"","baiduY":""},"roleInfo":{"id":"28b0acf3-76b0-4965-95cb-da2f5bc63bc2","name":"部長","normalizedName":"部長"},"expiration":"2020-01-17 10:22:23"}

此時content內(nèi)容是完整的

  • 將content內(nèi)容輸出到文本中
PS C:\Users\wweim> curl -h $header -uri $uri -method post -body $json -outfile "d:\content.txt"

d:\content.txt可看到輸出的內(nèi)容

其他用法:

# fotmat-list查看$hash
PS C:\Users\wweim> $hash | format-list
Name  : password
Value : 1

Name  : userName
Value : bz
#查看屬性
PS C:\Users\wweim> $hash.userName
bz
#屬性賦值
PS C:\Users\wweim> $hash.userName = "wwmin"
PS C:\Users\wweim> $hash

Name                           Value
----                           -----
userName                       wwmin
password                       1
#將請求結(jié)果保存到變量
PS C:\Users\wweim> $res=curl -h $header -uri $uri -method post -body $json | select content
PS C:\Users\wweim> $res

Content
-------
{"token":"eyJhbGc..."}
PS C:\Users\wweim> $res.Content
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy5..."}

將content內(nèi)容轉(zhuǎn)為對象ConvertFrom-json

PS C:\Users\wweim> $data = ConvertFrom-json -inputobject $res.content
PS C:\Users\wweim> $data.token
eyJhbGciOiJIUzI1NiIsInR5cCI....

你可以使用ConvertTo-Json轉(zhuǎn)回JSON格式

PS C:\Users\wweim> $data | convertto-json
{
    "token":  "eyJhbGciOiJIUzI1NiI...",
}

請求帶有token的uri, 其實就是在header中添加authorization對象

PS C:\Users\wweim> $data.token ="Bearer "+ $data.token
PS C:\Users\wweim> $heads = @{"authorization"=$data.token}
PS C:\Users\wweim> $uri="http://localhost:8001/api/ProjectInfo/preview?startYear=2019&endYear=2020"
PS C:\Users\wweim> curl -h $heads -uri $uri | select -ExpandProperty content

#返回的結(jié)果
[{"children":[],"name":"全部"]

到此,接口請求基本夠用

使用腳本文件

PS C:\Users\wweim> "hello world" >d:\hello.ps1

執(zhí)行

PS D:\> hello.ps1
hello.ps1 : 無法將“hello.ps1”項識別為 cmdlet、函數(shù)、腳本文件或可運行程序的名稱。請檢查名稱的拼寫,如果包括路徑,請確
保路徑正確,然后再試一次。
所在位置 行:1 字符: 1
+ hello.ps1
+ ~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (hello.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

沒有權(quán)限,也是安全機制,可參考官網(wǎng)

PS D:\> Get-ExecutionPolicy -list

        Scope ExecutionPolicy
        ----- ---------------
MachinePolicy       Undefined
   UserPolicy       Undefined
      Process       Undefined
  CurrentUser       Undefined
 LocalMachine    RemoteSigned

用管理員權(quán)限打開powershell,并輸入命令,然后選擇y

PS C:\WINDOWS\system32> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned

執(zhí)行策略更改
執(zhí)行策略可幫助你防止執(zhí)行不信任的腳本。更改執(zhí)行策略可能會產(chǎn)生安全風險,如 https:/go.microsoft.com/fwlink/?LinkID=135170
中的 about_Execution_Policies 幫助主題所述。是否要更改執(zhí)行策略?
[Y] 是(Y)  [A] 全是(A)  [N] 否(N)  [L] 全否(L)  [S] 暫停(S)  [?] 幫助 (默認值為“N”): y

說明:
Restricted 執(zhí)行策略不允許任何腳本運行。
AllSigned 和 RemoteSigned 執(zhí)行策略可防止 Windows PowerShell 運行沒有數(shù)字簽名的腳本

使用Windows PowerShell ISE編輯腳本

  • 介紹
    [百度百科]:Windows PowerShell 集成腳本環(huán)境 (ISE) 是 Windows PowerShell 的主機應用程序。在 Windows PowerShell ISE 中,可以在單一 Windows 圖形用戶界面中運行命令以及編寫、測試和調(diào)試腳本,該用戶界面具有多行編輯、Tab 補齊、語法著色、選擇性執(zhí)行、上下文相關幫助等功能,而且還支持從右到左書寫語言。此主機應用程序最多還可以包括八個會話。 可以自定義 Windows PowerShell ISE 的外觀。Windows PowerShell ISE 還有自己的 Windows PowerShell 配置文件,您可以在其中存儲在 Windows PowerShell ISE 中使用的函數(shù)、別名、變量和命令。
Windows PowerShell ISE
  • 如何打開
  1. 將文本文件保存為.ps1后綴文件之后,右鍵編輯即可打開
  2. 在win10搜索框中輸入ise
    ISE
  • 編輯命令
    有智能提示編寫代碼還是很爽的,比在命令行下輸入強太多
$login_uri = "http://localhost:8001/api/Account/login"
$header = @{"content-type"="application/json"}
$hash = @{userName="bz";password="1"}
$json = $hash | ConvertTo-Json
$res = Curl -uri $login_uri -h $header -Method post -Body $json | select -ExpandProperty Content
$content = ConvertFrom-Json $res

$authHeader= @{"authorization"="Bearer "+$content.token}
$year = Get-Date | select year
$info_uri="http://localhost:8001/api/ProjectInfo/preview?startYear="+($year.Year-1)+"&endYear="+$year.Year
$data = curl -h $authHeader -uri $info_uri | select -ExpandProperty content
$data # 此處僅為了在控制臺中顯示數(shù)據(jù)

正常執(zhí)行.

像命令一樣執(zhí)行腳本

怎樣像執(zhí)行一個命令一樣執(zhí)行一個腳本,不用輸入腳本的相對路徑或者絕對路徑,甚至*.ps1擴展名。
那就將腳本的執(zhí)行語句保存為別名吧:

PS D:\> Set-Alias testUri D:\hello.ps1

PS D:\> testUri
[{"children":[],"name":"全部"]

完美執(zhí)行.
到此powershell的使用curl發(fā)送請求的需求基本滿足.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 一、什么是CURL? cURL 是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、...
    茶藝瑤閱讀 4,821評論 0 6
  • 一、什么是CURL? cURL 是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議,如HTTP、FTP、...
    伊Summer閱讀 1,390評論 0 4
  • cURL是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具,支持很多協(xié)議和選項,如HTTP、FTP、TELNET等,能...
    司馬東陽閱讀 1,516評論 0 6
  • 原文地址:PHPcURL庫函數(shù)抓取頁面內(nèi)容(轉(zhuǎn))作者:巴克 cURL是一個利用URL語法規(guī)定來傳輸文件和數(shù)據(jù)的工具...
    司馬東陽閱讀 1,261評論 0 3
  • 好像關于Powershell說的已經(jīng)差不多了,所以最后一篇文章就來使用Powershell寫一些腳本,幫助我們完成...
    樂百川閱讀 2,213評論 1 10

友情鏈接更多精彩內(nèi)容