这是一个函数,可以轻松检查,还有一些选项可以改变行为。
function Test-Debug {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[switch]$IgnorePSBoundParameters
,
[Parameter(Mandatory = $false)]
[switch]$IgnoreDebugPreference
,
[Parameter(Mandatory = $false)]
[switch]$IgnorePSDebugContext
)
process {
((-not $IgnoreDebugPreference.IsPresent) -and ($DebugPreference -ne "SilentlyContinue")) -or
((-not $IgnorePSBoundParameters.IsPresent) -and $PSBoundParameters.Debug.IsPresent) -or
((-not $IgnorePSDebugContext.IsPresent) -and ($PSDebugContext))
}
}
以下是演示特定场景输出的代码:
function Test-InheritExplicit {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[switch]$IgnorePSBoundParameters
,
[Parameter(Mandatory = $false)]
[switch]$IgnoreDebugPreference
,
[Parameter(Mandatory = $false)]
[switch]$IgnorePSDebugContext
)
process {
Test-Debug @PSBoundParameters
}
}
function Test-InheritImplicit {
[CmdletBinding()]
param (
[Parameter(Mandatory = $false)]
[switch]$IgnorePSBoundParameters
,
[Parameter(Mandatory = $false)]
[switch]$IgnoreDebugPreference
,
[Parameter(Mandatory = $false)]
[switch]$IgnorePSDebugContext
)
process {
Test-Debug -IgnorePSBoundParameters:$IgnorePSBoundParameters -IgnorePSDebugContext:$IgnorePSDebugContext -IgnoreDebugPreference:$IgnoreDebugPreference
}
}
[hashtable[]]$testCases = 0..15 | %{
[hashtable]$new = @{}
if ($_ -band 1) {$new.Debug = [switch]$true}
if ($_ -band 2) {$new.IgnorePSBoundParameters = [switch]$true}
if ($_ -band 4) {$new.IgnoreDebugPreference = [switch]$true}
if ($_ -band 8) {$new.IgnorePSDebugContext = [switch]$true}
$new
}
[int]$t = 0
$testCases | %{
[hashtable]$testCase = $_
(New-Object -TypeName PSObject -Property @{
TestId = ++$t
Debug = [bool]$_.Debug
IgnorePSBoundParameters = [bool]$_.IgnorePSBoundParameters
IgnoreDebugPreference = [bool]$_.IgnoreDebugPreference
IgnorePSDebugContext = [bool]$_.IgnorePSDebugContext
TD = (Test-Debug @testCase)
TIE = (Test-InheritExplicit @testCase)
TII = (Test-InheritImplicit @testCase)
})
} | Format-Table TestId, Debug, IgnorePSBoundParameters, IgnoreDebugPreference, IgnorePSDebugContext, TD, TIE, TII -AutoSize
以下是上述代码的输出结果:
TestId Debug IgnorePSBoundParameters IgnoreDebugPreference IgnorePSDebugContext TD TIE TII
------ ----- ----------------------- --------------------- -------------------- -- --- ---
1 False False False False False False False
2 True False False False True True True
3 False True False False False False False
4 True True False False True True True
5 False False True False False False False
6 True False True False True True False
7 False True True False False False False
8 True True True False False False False
9 False False False True False False False
10 True False False True True True True
11 False True False True False False False
12 True True False True True True True
13 False False True True False False False
14 True False True True True True False
15 False True True True False False False
16 True True True True False False False