sho*_*inc 7 powershell import-module
我一直在尝试使用ShouldProcess方法编写支持-whatif的安全代码,这样我的用户就可以了解cmdlet在真正运行之前应该做什么.
但是我遇到了一些障碍.如果我用-whatif作为参数调用脚本,$ pscmdlet.ShouldProcess将返回false.一切都很好.如果我调用在同一文件中定义的cmdlet(具有SupportsShouldProcess = $ true),它也将返回false.
但是,如果我调用另一个模块中定义的cmdlet,我已使用Import-Module加载,它将返回true.-whatif上下文似乎没有传递给另一个模块中的调用.
我不想手动将标志传递给每个cmdlet.有没有人有更好的解决方案?
这个问题似乎与这个问题有关.但是,他们并没有谈论跨模块问题.
示例脚本:
#whatiftest.ps1
[CmdletBinding(SupportsShouldProcess=$true)]
param()
Import-Module -name .\whatiftest_module -Force
function Outer
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if( $pscmdlet.ShouldProcess("Outer"))
{
Write-Host "Outer ShouldProcess"
}
else
{
Write-Host "Outer Should not Process"
}
Write-Host "Calling Inner"
Inner
Write-Host "Calling InnerModule"
InnerModule
}
function Inner
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if( $pscmdlet.ShouldProcess("Inner"))
{
Write-Host "Inner ShouldProcess"
}
else
{
Write-Host "Inner Should not Process"
}
}
Write-Host "--Normal--"
Outer
Write-Host "--WhatIf--"
Outer -WhatIf
Run Code Online (Sandbox Code Playgroud)
模块:
#whatiftest_module.psm1
function InnerModule
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if( $pscmdlet.ShouldProcess("InnerModule"))
{
Write-Host "InnerModule ShouldProcess"
}
else
{
Write-Host "InnerModule Should not Process"
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
F:\temp> .\whatiftest.ps1
--Normal--
Outer ShouldProcess
Calling Inner
Inner ShouldProcess
Calling InnerModule
InnerModule ShouldProcess
--WhatIf--
What if: Performing operation "Outer" on Target "Outer".
Outer Should not Process
Calling Inner
What if: Performing operation "Inner" on Target "Inner".
Inner Should not Process
Calling InnerModule
InnerModule ShouldProcess
Run Code Online (Sandbox Code Playgroud)
为此,您可以使用我称之为"CallStack peeking"的技术.使用Get-PSCallStack来查看所谓的函数.每个项目都有一个InvocationInfo,其内部将是一个名为"BoundParameters"的属性.这个参数@每个级别.如果-WhatIf被传递给它们中的任何一个,你可以像-WhatIf一样传递给你的函数.
希望这可以帮助
| 归档时间: |
|
| 查看次数: |
2264 次 |
| 最近记录: |