PowerShell脚本编写与优化技巧
1. 支持 -WhatIf 和 -Confirm 参数
在PowerShell中,若要支持标准的 -WhatIf 和 -Confirm 参数,并访问以cmdlet为中心的支持功能,可按以下步骤操作:
- 确保脚本或函数声明了 [CmdletBinding()] 属性。
- 通过 $psCmdlet 自动变量访问引擎功能。
示例代码如下:
function Invoke-MyAdvancedFunction
{
[CmdletBinding(SupportsShouldProcess = $true)]
param()
if($psCmdlet.ShouldProcess("test.txt", "Remove Item"))
{
"Removing test.txt"
}
Write-Verbose "Verbose Message"
}
当运行 Invoke-MyAdvancedFunction -WhatIf 时,会输出:
What if: Performing operation "Remove Item" on Target "test.txt".
若命令会产生高影响结果,需谨慎评估,可调用 $psCmdlet.ShouldContinue() 方法。
超级会员免费看
订阅专栏 解锁全文
128

被折叠的 条评论
为什么被折叠?



