My Technical Notes

Saturday, 21 January 2017

PowerShell `Get-ConfirmImpact` Function

In PowerShell, there is no easy way to find out the `ComfirmImpact` of a command. For that, I have implemented the following function `Get-ConfirmImpact`:


Function Get-ConfirmImpact {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]$Command
    )
    
    Begin {
        $ErrorActionPreference = 'Stop';
    }
    
    Process {
        $commandObj = (Get-Command $Command);
        
        if ($commandObj.CommandType -eq 'Alias') {
            return Get-ConfirmImpact $commandObj.Definition;
        } else {
        
            $attrs = & {
                if ($commandObj.ImplementingType) {
                    $commandObj.ImplementingType.GetCustomAttributes($true);
                } elseif ($commandObj.ScriptBlock) {
                    $commandObj.ScriptBlock.Attributes
                }
            };
            
            $attrs | 
                ? { $_ -is [System.Management.Automation.CmdletCommonMetadataAttribute] } | 
                % { $_.ConfirmImpact };
        }
    }
}

To use it, you pass a command name to the function:


Get-ConfirmImpact Move-Item

which will return `Medium`;

There is also a method to get the `ConfirmImpact` of a function within itself.

No comments: