Skip to content

Instantly share code, notes, and snippets.

@indented-automation
Last active February 29, 2024 07:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indented-automation/14b08915955c618fd2ddfd6cff51f92a to your computer and use it in GitHub Desktop.
Save indented-automation/14b08915955c618fd2ddfd6cff51f92a to your computer and use it in GitHub Desktop.
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