Skip to content

Instantly share code, notes, and snippets.

@ChrisLGardner
Forked from Jaykul/Hide-FromDebugger.ps1
Created July 31, 2017 08:19
Show Gist options
  • Save ChrisLGardner/5b094a51839f5306d88cd18e5157f3e3 to your computer and use it in GitHub Desktop.
Save ChrisLGardner/5b094a51839f5306d88cd18e5157f3e3 to your computer and use it in GitHub Desktop.
Have you ever wished you could hide a few commands from the PowerShell step-through?
<#
.SYNOPSIS
Wrap commands with DebuggerNonUserCode attribute to prevent the PowerShell debugger stepping into them
.DESCRIPTION
Generates proxy functions that wrap the original commands, and put an attribute on the proxy to prevent the debugger stopping.
.EXAMPLE
Get-Command -Module Pester | Hide-FromDebugger
Hides all pester functions from the debugger, so you can debug in your code without stepping into Pester functions.
#>
[CmdletBinding()]
param(
# The command to hide from the debugger
[Parameter(ValueFromPipeline)]
[System.Management.Automation.CommandInfo]
$Command,
[ValidateSet("DebuggerNonUserCode","DebuggerStepThrough","DebuggerHiddenAttribute")]
[string]$Attribute = "DebuggerStepThrough"
)
begin {
$ProxyFactory = [System.Management.Automation.ProxyCommand]
}
process {
$CommandName = $Command.Name
$CmdletBindingAttribute = $ProxyFactory::GetCmdletBindingAttribute($Command)
$ParamBlock = $ProxyFactory::GetParamBlock($Command)
$Begin = $ProxyFactory::GetBegin($Command)
$Process = $ProxyFactory::GetProcess($Command)
$End = $ProxyFactory::GetEnd($Command)
if($DynamicParam = $ProxyFactory::GetDynamicParam($Command)) {
$DynamicParam = "dynamicparam {`n$DynamicParam}"
}
if($Command.ModuleName) {
$Begin = $Begin -replace "'$CommandName'", "'$($Command.ModuleName)\$CommandName'"
$DynamicParam = $DynamicParam -replace "'$CommandName'", "'$($Command.ModuleName)\$CommandName'"
} else {
$CommandName = $CommandName + "Ex"
Write-Warning "Cannot safely override functions that aren't in a module. Creating wrapper as $CommandName"
}
$Proxy = @"
function global:$CommandName {
[System.Diagnostics.$Attribute()]
$CmdletBindingAttribute
param(
$ParamBlock
)
$DynamicParam
begin {
$Begin
}
process {
$Process
}
end {
$End
}
<#
.ForwardHelpTargetName $($Command.ModuleName)\$CommandName
.ForwardHelpCategory $($Command.Commandtime)
#>
}
"@
Invoke-Expression $Proxy
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment