如何在powershell中使用“dry-run" [英] how to use 'dry-run' in powershell

查看:38
本文介绍了如何在powershell中使用“dry-run"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是一个初学者,dry-run 对于制作要测试的参数非常有用,有人能告诉我如何简单地使用它吗?我用谷歌搜索,但关于它的用途的结果很少.

I'm just a starter, dry-run is pretty useful to make a parameter to test, can any body tell me how to use it with an easy way? I googled that but few results on its uses.

非常感谢

推荐答案

在现有 cmdlet 上使用

明确提供 -WhatIf 参数:

Use on existing cmdlets

Explicitly supply the -WhatIf parameter:

rm foo.txt -WhatIf

结果:

What if: Performing operation "Remove File" on Target "C:\temp\foo.txt".

在函数或脚本中的现有 cmdlet 上使用

SupportsShouldProcess 属性自动将 -WhatIf 传播到支持的 cmdlet:

Use on existing cmdlets within a function or script

SupportsShouldProcess attribute automatically propagates -WhatIf to supported cmdlets:

function do-stuff
{
    [CmdletBinding(SupportsShouldProcess=$True)]
    param([string]$file)
    Remove-Item $file
}

do-stuff foo.txt -WhatIf

结果:

What if: Performing operation "Remove File" on Target "C:\temp\foo.txt".

在您自己的代码块上使用

显式使用ShouldProcess()方法判断-WhatIf是否通过:

function do-stuff
{
    [CmdletBinding(SupportsShouldProcess=$True)]
    param([string]$file)
    if ($PSCmdlet.ShouldProcess($file)) {
        Write-Host "Deleting file"
        Remove-Item $file
    }
}

do-stuff foo.txt -WhatIf

结果:

What if: Performing operation "do-stuff" on Target "foo.txt".

用于相同模块中的嵌套函数

SupportsShouldProcess 属性自动将 -WhatIf 传播到嵌套函数:

Use on Nested functions in the same module

SupportsShouldProcess attribute automatically propagates -WhatIf to nested functions:

function do-stuff
{
    [CmdletBinding(SupportsShouldProcess=$True)]
    param([string]$file)
    if ($PSCmdlet.ShouldProcess($file)) {
        Write-Host "Deleting file"
        Remove-Item $file
    }
    inner "text"
}

function inner
{
    [CmdletBinding(SupportsShouldProcess=$True)]
    param([string]$s)
    if ($PSCmdlet.ShouldProcess($s)) {
        Write-Host "Inner task"
    }
    $s | out-file "temp9.txt"
}
do-stuff foo.txt -WhatIf

结果:

What if: Performing operation "do-stuff" on Target "foo.txt".
What if: Performing operation "inner" on Target "text".
What if: Performing operation "Output to File" on Target "temp9.txt".

用于不同模块中的嵌套函数

不幸的是,-WhatIf 不会自动传播到不同模块中定义的函数.请参阅 Powershell:如何获取 -whatif传播到另一个模块中的 cmdlet 以供讨论和解决此问题.

Use on Nested functions in a different module

Unfortunately, -WhatIf does not propagate automatically to functions defined in a different module. See Powershell: How to get -whatif to propagate to cmdlets in another module for discussion and workaround for this.

这篇关于如何在powershell中使用“dry-run"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆