本文介绍了如何从 -WhatIf 处理中排除块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个 Powershell cmdlet,它需要执行一个命令并将其 stderr 输出存储到一个临时文件以供以后处理.此输出列出了 cmdlet 稍后可能会使用的 COM 端口.

I'm writing a Powershell cmdlet that needs to execute a command and store its stderr output to a temporary file for later processing. This output lists COM ports that the cmdlet may use later.

# mostly side-effect-free information gathering
$info = [IO.Path]::GetTempFileName()
info-gather.exe 2>$info
Get-Content $info | ForEach-Object {
    # processing
}
Remove-Item $info

# serious things with serious side effects start here

我希望这个 cmdlet 实现 -WhatIf,因为它会产生重要的副作用.然而,-WhatIf 行为接管了 info-gather.exe 命令并且它根本就不会被执行.相反,它打印:

I would like this cmdlet to implement -WhatIf since it will have non-trivial side effects. However, the -WhatIf behavior takes over the info-gather.exe command and it is simply never executed. Instead, it prints:

假设:在目标temp\path\to\tmp78A4.tmp"上执行输出到文件"操作

因为这个命令永远不会执行,内部处理也不会发生,我的其余有实际副作用的 cmdlet 没有执行,因为它不知道使用哪个端口,使得 -WhatIf 基本上没用.

Because this command is never executed, the inner processing doesn't happen either, and the rest of my cmdlet that has actual side effects isn't executed because it doesn't know which ports to use, making -WhatIf largely useless.

如何绕过此块的 -WhatIf 而不在 cmdlet 的其余部分覆盖它?

How can I bypass -WhatIf for this block without overriding it in the rest of the cmdlet?

推荐答案

您可以使用 try...finally 设置然后重置 $WhatIfPreference 变量.

You could use try...finally to set and then reset the $WhatIfPreference variable.

$script:oldWhatIfPrefernence = $WhatIfPreference
try {
    $WhatIfPreference = $false

    $info = [IO.Path]::GetTempFileName()
    info-gather.exe 2>$info
    Get-Content $info | ForEach-Object {
        # processing
    }
    Remove-Item $info
} finally {
    $WhatIfPreference = $script:oldWhatIfPreference
}

如果您没有使用 2> 重定向,还有另一种方法.您可以将 -WhatIf 开关显式传递给许多 cmdlet,并仅针对该部分覆盖 -WhatIf.

If you weren't using the 2> redirection, there is another way. You can pass the -WhatIf switch explicitly to many cmdlets and override -WhatIf for just that part.

Remove-Item $info -WhatIf:$false

不过,不涉及临时文件的 zneak 的答案也非常优雅.

Though, zneak's answer that doesn't involve a temporary file is pretty elegant too.

这篇关于如何从 -WhatIf 处理中排除块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 19:20