我正在编写一个 Powershell cmdlet,它需要执行命令并将其 stderr 输出存储到临时文件中以供以后处理。此输出列出了 cmdlet 稍后可能使用的 COM 端口。
# 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
命令,它根本就不会被执行。相反,它打印:
如果:在目标“temp\path\to\tmp78A4.tmp”上执行“输出到文件”操作
因为这个命令永远不会执行,所以内部处理也不会发生,并且具有实际副作用的其余 cmdlet 也不会执行,因为它不知道要使用哪些端口,使得-WhatIf
基本上没用。
我怎样才能绕过-WhatIf
对于此块而不在 cmdlet 的其余部分中覆盖它?
你可以使用try...finally
设置然后重置$WhatIfPreference多变的 https://technet.microsoft.com/en-us/library/hh847796.aspx.
$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
仅针对那部分。
Remove-Item $info -WhatIf:$false
Though, 兹内克的回答 https://stackoverflow.com/a/36292606/2392683不涉及临时文件也非常优雅。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)