Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A bit of fun, replaces full command names with aliases
using namespace System.Management.Automation.Language
function Enable-ScriptAlias {
<#
.SYNOPSIS
Replace all aliased commands in a script with the alias name.
.DESCRIPTION
Replace all aliased commands in a script with the alias name.
#>
[CmdletBinding(DefaultParameterSetName = 'FromString')]
param (
# A string containing a script.
[Parameter(Mandatory, ValueFromPipeline, ParameterSetName = 'FromString')]
[string]$String,
# The path to a file containing a script.
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'FromPath')]
[Alias('FullName')]
[string]$Path,
# A script block describing the content to convert.
[Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'FromScript')]
[ScriptBlock]$ScriptBlock,
# Defines the sort order for aliases which determines how aliases are selected when multiple are available.
# By default a random alias is chosen for each command.
#
# Setting Selector to an empty script block will disable sorting, using the first alias returned by `Get-Alias` in each case.
[ScriptBlock]$Selector = { Get-Random }
)
process {
if ($String) {
$ast = [Parser]::ParseInput(
$String,
[ref]$null,
[ref]$null
)
} elseif ($Path) {
$ast = [Parser]::ParseFile(
$Path,
[ref]$null,
[ref]$null
)
} else {
$ast = $ScriptBlock.Ast
}
$script = $ast.Extent.Text
$ast.FindAll(
{
param ( $node )
$node -is [System.Management.Automation.Language.CommandAst] -and
(Get-Alias -Definition $node.GetCommandName() -ErrorAction SilentlyContinue)
},
$true
) | ForEach-Object {
$_.CommandElements[0]
} | Sort-Object {
$_.Extent.StartOffset
} -Descending | ForEach-Object {
$alias = Get-Alias -Definition $_.Value | Sort-Object $Selector | Select-Object -First 1
$script = $script.Remove($_.Extent.StartOffset, $_.Value.Length).Insert($_.Extent.StartOffset, $alias.Name)
}
$script
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment