
假設我有一個包含以下內容的 .ps1 (實際內容並不重要):
param(
[Parameter(Mandatory=$true)]
[string]
$someArgument
)
# Do something risky
Remove-Item "c:\path\$someArgument.txt"
我想為我的腳本(或實際上的任何方法)添加一條確認訊息,該訊息可以關閉(預設會開啟)。
.\myscript.ps1 "foo" -Confirm:$false
我怎樣才能做到這一點 ?
答案1
對於高級功能,您可以使用稱為 ShouldProcess 的東西。
在腳本頂部,您可以新增一個名為 [CmdletBinding] 的屬性
[CmdletBinding(
SupportsShouldProcess=$true,
ConfirmImpact="High"
)]
一旦完成,在函數體內,您需要使用 if 語句
if ($pscmdlet.ShouldProcess($thingIamGoingToChange))
查看說明 about_advanced_functions 和說明 about_functions_cmdletbinding。