22
如何在PowerShell中強制使用參數?如何在PowerShell中強制使用參數?
如何在PowerShell中強制使用參數?如何在PowerShell中強制使用參數?
你在這樣每個參數上面的屬性指定:
function Do-Something{
[CmdletBinding()]
param(
[Parameter(Position=0,mandatory=$true)]
[string] $aMandatoryParam,
[Parameter(Position=1,mandatory=$true)]
[string] $anotherMandatoryParam)
process{
...
}
}
要使某個參數強制添加一個「強制性= $真」的參數說明。要使參數可選,只需將「強制性」語句退出即可。
該代碼同時適用於腳本和功能參數:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$aMandatoryParameter,
[String]$nonMandatoryParameter,
[Parameter(Mandatory=$true)]
[String]$anotherMandatoryParameter
)
確保「參數」語句是第一個(除了命令和空行)無論是在腳本或函數。
您可以使用「獲取幫助」 cmdlet來驗證參數已正確定義:
PS C:\> get-help Script.ps1 -full
[...]
PARAMETERS
-aMandatoryParameter <String>
Required? true
Position? 1
Default value
Accept pipeline input? false
Accept wildcard characters?
-NonMandatoryParameter <String>
Required? false
Position? 2
Default value
Accept pipeline input? false
Accept wildcard characters?
-anotherMandatoryParameter <String>
Required? true
Position? 3
Default value
Accept pipeline input? false
Accept wildcard characters?
只是好奇,會發生什麼的時候可以說一個.BAT調用.PS1和強制性參數是左出。 PS1的迴應/錯誤是什麼樣的? – Quanda
當您在未提供必需參數的情況下調用PowerShell腳本時,腳本會在執行之前以交互方式提示您,例如, 「爲以下參數提供值:aMandatoryParameter:」 – llmora