PowerShell เป็นหนึ่งในเครื่องมือสคริปติ้งที่ทรงพลังที่สุดที่ Microsoft สร้างขึ้น ในบทความนี้ เราจะแชร์ว่า PWSH.exe คืออะไร และรายการ PWSH syntax ที่สำคัญ ผมเชื่อว่าผู้หลายคนเคยใช้ Windows PowerShell แต่ PWSH ตอนนี้เป็นเครื่องมือสคริปติ้งข้ามแพลตฟอร์มที่ทำงานบน Windows, macOS และ Linux อย่างไรก็ตาม ไม่ได้รับการรองรับบน WSL เช่น Windows Subsystem on Linux และการพยายามตั้งค่า PWSH เป็น login shell จะทำให้ WSL ไม่เสถียร
PWSH.EXE คืออะไร?

ก่อนเริ่ม ให้ชี้แจงรายละเอียดหนึ่งอย่าง PWSH.EXE คือชื่อใหม่สำหรับ PowerShell ตั้งแต่ version 6 เรียกว่า PowerShell Core มันชื่อเดิมว่า powershell.exe ซึ่งคุณคงเคยเห็นติดตั้งใน Windows (version 5.1) ไม่แปลกใจที่ทุกครั้งที่คุณเปิด PowerShell ใน Windows คุณจะได้ข้อความ:
"Try the new cross-platform PowerShell https://aka.ms/pscore6."
คุณสามารถอ่านเกี่ยวกับความแตกต่างระหว่าง PowerShell และ PowerShell Core ได้
มาถึงวันนี้ PowerShell ถึง version 7 ซึ่งเป็นการเปลี่ยนแปลงใหญ่เมื่อเทียบกับ version 6 และใช้ .NET Core 3 แทน .Net Framework หากคุณอยากลอง เรียนรู้วิธีติดตั้ง PowerShell 7.0 บน Windows 10
PWSH Syntax ที่สำคัญ
-File | -f: หากคุณมีคำสั่งในไฟล์สคริปต์ คุณสามารถใช้มันเป็น input คุณยังสามารถใช้ arguments สำหรับไฟล์เมื่อเหมาะสม
pwsh -File .\test.ps1 -TestParam $env:windir
-Command | -c: ใช้เพื่อรันคำสั่งหรือ ScriptBlock ScriptBlock คือชุดฟังก์ชันที่ล้อมรอบด้วย {}
pwsh -Command {Get-WinEvent -LogName security}
หรือ
@' "in" "hi" | % { "$_ there" } "out" '@ | powershell -NoProfile -Command -
-EncodedCommand | -e | -ec: ใช้เมื่อมีความจำเป็นต้องใช้ quotation marks หรือ curly braces ที่ซับซ้อน
$command = 'dir "c:\program files" ' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) pwsh -encodedcommand $encodedCommand
-Login | -l: บน Linux และ macOS เริ่ม PowerShell เป็น login shell โดยใช้ /bin/sh เพื่อรัน login profiles เช่น /etc/profile และ ~/.profile ไม่適用กับ Windows
คุณจะต้องตรวจสอบ absolute path ที่แสดงภายใต้ /etc/shells คุณสามารถใช้ utility chsh เพื่อตั้งค่า shell ของผู้ใช้ปัจจุบันเป็น pwsh
chsh -s /usr/bin/pwsh
-SettingsFile | -settings
หากคุณต้องการเขียนทับ global settings ด้วย local project settings คุณสามารถระบุ settings file โดยใช้ตัวเลือกนี้ System-wide settings มีอยู่ใน powershell.config.json
pwsh -SettingsFile c:\myproject\powershell.config.json
รายการ PWSH Syntax ครบถ้วน
pwsh[.exe] [[-File] <filePath> [args]] [-Command { - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>] } ] [-ConfigurationName <string>] [-CustomPipeName <string>] [-EncodedCommand <Base64EncodedCommand>] [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}] [-Interactive] [-Login] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile] [-OutputFormat {Text | XML}] [-SettingsFile <SettingsFilePath>] [-STA] [-Version] [-WindowStyle <style>] [-WorkingDirectory <directoryPath>] pwsh[.exe] -h | -Help | -? | /?
หากต้องการรายละเอียดเพิ่มเติม คุณสามารถเยี่ยมชม docs.microsoft.com ได้
