Created
July 29, 2017 23:01
-
-
Save Jaykul/aa768dbcd2caa88b0feab797766acae9 to your computer and use it in GitHub Desktop.
Have you ever wished you could hide a few commands from the PowerShell step-through?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.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