0

ทดสอบส่ง Line Notify ด้วย curl ใน PowerShell

PowerShell คืออะไร ?

PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-source and cross-platform on 18 August 2016 with the introduction of PowerShell Core.[5] The former is built on .NET Framework while the latter on .NET Core.

ที่มา : https://en.wikipedia.org/wiki/PowerShell

ถ้าพูดให้เข้าใจง่าย ๆ คือ เป็น Command Shell รูปใหม่ของ Microsoft ที่คล้ายกับ command line แต่สามารถทำอะไรได้มากกว่า ทำงานบน .NET Framework สามารถจัดการบริหาร Windows ได้ผ่านคำสั่ง cmdlets ทีนี้ถ้าใครคุ้นชินกับ Shell อื่น ๆ ใน Linux หรือ Unix Base ก็จะใช้งานผ่าน Shell อาทิ

  • Bourne shell (sh)
  • Debian Almquist shell (dash)
  • Bourne-Again shell (bash)
  • C shell (csh)

ซึ่ง Shell เหล่านี้มันมี curl ให้ใช้ใน Distro นั้น ๆ อยู่แล้ว (คือติดตั้งมาก่อน ถ้าไม่มีก็ติดตั้งเพิ่มตามแต่ละ Distro ไป) แล้ว curl คืออะไร

curl is a tool to transfer data from or to a server, using one of the supported
protocols (DICT, FILE, FTP, FTPS, GOPHER, HTTP, HTTPS,IMAP, IMAPS, LDAP, LDAPS, POP3,POP3S, RTMP, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET and TFTP).The command is designed to work without user interaction.

ไปตามอ่านวิธีใช้งานกันได้ที่ https://devahoy.com/blog/2016/11/getting-started-with-curl

โดย curl ไม่ได้มีมาพร้อมกับ PowerShell แต่ถ้าเราต้องการใช้คำสั่งนี้ใน PowerShell ที่ให้ผลลัพธ์เช่นเดียวกับ curl หล่ะทำไง ^__^  (มีวิธีติดตั้ง curl ที่เป็นเวอร์ชั่น Windows อยู่แต่ก็นั่นหล่ะ : https://curl.haxx.se/ )

ซึ่ง PowerShell ก็มีคำสั่งที่ใช้งานได้ในลักษณะเดียวกันกับ curl ชื่อว่า Invoke-WebRequest รายละเอียดลึก ๆ ตามไปอ่านที่นี่นะครับ ซึ่ง PowerShell ตั้งแต่เวอร์ชั่น 5.0 เป็นต้นมาสามารถใช้ Alias curl แทน Invoke-WebRequest ได้ ทดสอบก่อนว่าเราใช้ PowerShell เวอร์ชั่นอะไร

$PSversiontable

เกริ่นมาเยอะขิง ๆ อยากแค่ทดสอบ Line Notify เอง ตัดจบหล่ะกันนะ ^___^ มีงานงอก ตามตัวอย่างเอกสารของทางไลน์เวลาเราจะทดสอบส่ง Line Notify สามารถใช้คำสั่งตามนี้

curl -X POST -H 'Authorization: Bearer [access_token]' -F 'message=foobar' https://notify-api.line.me/api/notify

ส่วนใน PowerShell เราทดสอบก่อนว่าสามารถใช้ curl ได้หรือไม่จากคำสั่งนี้

Get-Alias -Definition Invoke-WebRequest | Format-Table -AutoSize

ถ้าขึ้นแบบนี้เป็นอันว่าเราสามารถใช้ curl แทน(Alias) Invoke-WebRequest ได้เลย งั้นก็ทดสอบกันเลย ส่ง Line Notify กัน

curl -Uri 'https://notify-api.line.me/api/notify' -Method Post -Headers @{Authorization = 'Bearer [access_token]'} -Body @{message = 'PowerShell Notification'}

ส่งสำเร็จก็จะขึ้นผลลัพธ์ตามนี้

จบปิ๊ง ^__^ (เราตัดเรื่องการขอ Access Token ไปนะ เชื่อว่าคงหาอ่านได้ไม่ยากก)
ป.ล.1  มือใหม่ PowerShell
ป.ล.2 มือใหม่หัดรัก(หัดเจ็บด้วย)