PowerShell là một trong những công cụ scripting mạnh nhất của Microsoft. Bài này chia sẻ PWSH.exe là gì và liệt kê các cú pháp PWSH quan trọng. Nhiều người dùng Windows PowerShell, nhưng PWSH giờ là công cụ scripting đa nền tảng (Windows, macOS, Linux). Không hỗ trợ trên WSL (Windows Subsystem for Linux), đặt PWSH làm login shell sẽ làm WSL không ổn định.
PWSH.EXE là gì?
Trước hết, làm rõ: PWSH.EXE là tên mới của PowerShell. Từ phiên bản 6 gọi là PowerShell Core. Trước đó tên powershell.exe (phiên bản 5.1 tích hợp sẵn Windows). Mỗi lần mở PowerShell trên Windows, bạn thấy thông báo: "Try the new cross-platform PowerShell https://aka.ms/pscore6."
Hiện PowerShell đã đến phiên bản 7, thay đổi lớn so với v6, dùng .NET Core 3 thay vì .NET Framework. Xem cách cài PowerShell 7.0 trên Windows 10.
Các cú pháp PWSH quan trọng
-File | -f: Chạy script từ file, có thể truyền tham số.
pwsh -File .\test.ps1 -TestParam $env:windir
-Command | -c: Thực thi lệnh hoặc ScriptBlock (hàm trong {}).
pwsh -Command {Get-WinEvent -LogName security}
Hoặc:
@' "in" "hi" | % { "$_ there" } "out" '@ | powershell -NoProfile -Command -
-EncodedCommand | -e | -ec: Dùng khi cần dấu ngoặc phức tạp hoặc ngoặc nhọn.
$command = 'dir "c:\program files" ' $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) $encodedCommand = [Convert]::ToBase64String($bytes) pwsh -encodedcommand $encodedCommand
-Login | -l: Trên Linux/macOS, khởi động PowerShell như login shell, dùng /bin/sh thực thi profile (/etc/profile, ~/.profile). Không áp dụng Windows. Kiểm tra đường dẫn tuyệt đối trong /etc/shells, dùng chsh đặt shell hiện tại:
chsh -s /usr/bin/pwsh
-SettingsFile | -settings
Ghi đè cài đặt toàn cục bằng cài đặt dự án cục bộ. Cài đặt hệ thống ở powershell.config.json.
pwsh -SettingsFile c:\myproject\powershell.config.json
Danh sách đầy đủ cú pháp PWSH
pwsh[.exe] [[-File][args]] [-Command { - | [-args ] | [ ] } ] [-ConfigurationName ] [-CustomPipeName ] [-EncodedCommand ] [-ExecutionPolicy ] [-InputFormat {Text | XML}] [-Interactive] [-Login] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile] [-OutputFormat {Text | XML}] [-SettingsFile ] [-STA] [-Version] [-WindowStyle