上QQ阅读APP看书,第一时间看更新
There's more...
If you want to add your own WhatIf and Confirm parameters, you don't need to implement them like normal parameters, shown as follows:
# Do not do this
function Test-WrongRiskMitigation
{
param
(
[switch]
$WhatIf
)
if ($WhatIf)
{
Write-Host "Simulating shredding of evidence"
}
}
Instead, you can make use of the CmdletBinding attribute, which automatically enables all common parameters and is able to add WhatIf and Confirm properly:
function Test-RiskMitigation
{
[CmdletBinding(SupportsShouldProcess)]
param ( )
if ($PSCmdlet.ShouldProcess('Target object, here: The evidence','Action, here: Shred'))
{
Write-Host -ForegroundColor Red -Object 'Shredding evidence...'
}
}
Test-RiskMitigation -WhatIf
Test-RiskMitigation
This way, you can simply react to the cmdlet emitting a confirmation message as a user. There's no additional implementation necessary apart from using the cmdlet binding and the automatic PSCmdlet variable.