如何在 Windows PowerShell 中獲取命令行參數
- 在 PowerShell 腳本中定義參數
- 在 PowerShell 腳本中使用命名參數
- 在 PowerShell 腳本中為參數分配默認值
- 在 PowerShell 腳本中使用開關參數
- 在 PowerShell 腳本中使用強制參數

我們使用名為 param()
的 Windows PowerShell 參數函數來處理參數。Windows PowerShell 參數函數是任何腳本的基本組成部分。參數是開發者讓腳本使用者在執行時提供輸入的方式。
在這篇文章中,您將學習如何使用參數函數創建腳本、使用它們以及一些建立參數的最佳實踐。
在 PowerShell 腳本中定義參數
管理員可以使用參數函數 param()
為腳本和函數創建參數。函數包含一個或多個由變數定義的參數。
Hello_World.ps1
:
param(
$message
)
然而,為了確保參數僅接受您需要的輸入類型,最佳實踐建議使用參數區塊 [Parameter()]
將數據類型分配給參數,並用方括號 []
將數據類型括起來放在變數之前。
Hello_World.ps1
:
param(
[Parameter()]
[String]$message
)
在上面的 Hello_World.ps1
範例中,變數 message
只會在傳入的值具有 String
數據類型時接受傳遞的值。
在 PowerShell 腳本中使用命名參數
使用參數函數的一種方式是通過參數名稱——這種方法稱為命名參數。當通過命名參數調用腳本或函數時,我們使用變數名作為參數的完整名稱。
我們創建了一個 Hello_World.ps1
,並在這個範例中在參數函數內部定義了變數。請記住,我們可以在參數函數中放入一個或多個變數。
Hello_World.ps1
:
param(
[Parameter()]
[String]$message,
[String]$emotion
)
Write-Output $message
Write-Output "I am $emotion"
然後我們可以在執行 .ps1
文件時將命名參數作為參數。
.\Hello_World.ps1 -message 'Hello World!' -emotion 'happy'
輸出:
Hello World!
I am happy
在 PowerShell 腳本中為參數分配默認值
我們可以通過在腳本內部為參數賦予一個值來預先分配一個值給參數。然後,當不從執行行傳遞值運行腳本時,將使用腳本內部定義的變數的默認值。
param(
[Parameter()]
[String]$message = "Hello World",
[String]$emotion = "happy"
)
Write-Output $message
Write-Output "I am $emotion"
.\Hello_World.ps1
輸出:
Hello World!
I am happy
在 PowerShell 腳本中使用開關參數
我們可以使用的另一個參數是由 [switch]
數據類型定義的開關參數。開關參數用於二進制或布林值以指示 true
或 false
。
Hello_World.ps1
:
param(
[Parameter()]
[String]$message,
[String]$emotion,
[Switch]$display
)
if ($display) {
Write-Output $message
Write-Output "I am $emotion"
}
else {
Write-Output "User denied confirmation."
}
我們可以使用下面的語法調用帶有腳本參數的腳本。
.\Hello_World.ps1 -message 'Hello World!' -emotion 'happy' -display:$false
輸出:
User denied confirmation.
在 PowerShell 腳本中使用強制參數
在執行腳本時,通常會有一個或多個必須使用的參數。我們可以通過在參數區塊 [Parameter()]
中添加 Mandatory
屬性來使參數變為強制性。
Hello_World.ps1:
param(
[Parameter(Mandatory)]
[String]$message,
[String]$emotion,
[Switch]$display
)
if ($display) {
Write-Output $message
Write-Output "I am $emotion"
}
else {
Write-Output "User denied confirmation."
}
在執行 Hello_World.ps1
時,Windows PowerShell 將不允許腳本運行並提示您輸入一個值。
.\Hello_World.ps1
輸出:
cmdlet hello_world.ps1 at command pipeline position 1
Supply values for the following parameters:
message:
Marion specializes in anything Microsoft-related and always tries to work and apply code in an IT infrastructure.
LinkedIn