Created
February 1, 2019 00:48
-
-
Save fearthecowboy/172e7e93328268b3241fddf001d02e52 to your computer and use it in GitHub Desktop.
A better new-alias for PowerShell
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 | |
Creates a new alias. Better than original New-Alias | |
.DESCRIPTION | |
Creates a new Function Alias. Unlike the original New-Alias, this will let you | |
create an alias that can be a command line or script, in a single command. | |
.PARAMETER Name | |
Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number. | |
.PARAMETER Value | |
Specifies the name of the cmdlet or command element that is being aliased. | |
This may be a scriptblock, or a string, or it will consume the remaining | |
arguments as a command line. | |
If a scriptblock is given, use of $args will gain access to the arguments | |
passed to the alias | |
If a string is given and $args is not in the string, $args will be added to the | |
end of the command. | |
If a string is given and $args is present, it will not add $args on the end. | |
(this preserves functionality with the original new-alias) | |
.EXAMPLE | |
Creates an alias "List" which just calls Get-ChildItem with whatever arugments | |
are passed. | |
C:\PS> New-Alias List Get-ChildItem | |
.EXAMPLE | |
Creates an alias "List" which just calls Get-ChildItem with whatever arugments | |
are passed. | |
C:\PS> New-Alias List {Get-ChildItem $args} | |
.EXAMPLE | |
Creates an alias "List" which just calls Get-ChildItem with whatever arugments | |
are passed, and then extracts out the full name of each file | |
C:\PS> New-Alias List { get-ChildItem $args |% {$_.FullName} } | |
.EXAMPLE | |
Creates an alias "d" which just calls dir with whatever arugments | |
are passed, and tacks on an exclude. | |
C:\PS> New-Alias d 'dir $args -exclude *.json' | |
#> | |
function new-alias([parameter(mandatory=$true, position=0)][string]$name,[parameter(mandatory=$true, position=1, ValueFromRemainingArguments=$true)]$value ) { | |
if($value[0] -is [Scriptblock]) { | |
set-Item "function:global:$name" $value[0] | |
} else { | |
if( "$value".indexOf('$args') -gt -1) { | |
set-Item "function:global:$name" ([ScriptBlock]::Create("$value")) | |
} else { | |
set-Item "function:global:$name" ([ScriptBlock]::Create("$value `$args")) | |
} | |
} | |
} |
Author
fearthecowboy
commented
Feb 1, 2019
new-alias sort-clipboard {get-clipboard | Sort-Object | get-unique | Set-Clipboard}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment