Skip to content

Instantly share code, notes, and snippets.

@XPlantefeve
Last active February 14, 2019 09:17
Show Gist options
  • Save XPlantefeve/9f1090df3b4446e2f22215eb2730a837 to your computer and use it in GitHub Desktop.
Save XPlantefeve/9f1090df3b4446e2f22215eb2730a837 to your computer and use it in GitHub Desktop.
Do-Something, the lazy typist way
# Laziness is a great gift
# Every function will have the exact same definition, so we won't bother
# copypasting.
$FunctionBody = {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory, Position = 0, ValueFromPipeline)]
[object[]]$inputObject
)
begin {
$Verb = $MyInvocation.MyCommand.Verb
}
process {
foreach ($Object in $inputObject) {
$command = Get-Command -Verb $Verb -ParameterType $Object.GetType()
if ($command) {
if ($PSCmdlet.ShouldProcess($Object.Name, $verb)) {
New-Alias -Name _do -Value $command.Name
$inputObject | _do
Remove-Item alias:_do
}
} else {
Write-Error ('no command {0} found for the type {1}.' -f $Verb, $Object.GetType().Name)
}
}
}
end {}
}
# A few verbs to create shortcuts of, expand at will.
# Some verbs have well known defined aliases. Those get a special treatment.
$Verbs = @(
'Stop'
'Restart'
'Remove'
'Import'
,('Start','Strt')
,('Copy','Cpy')
)
foreach ($verb in $Verbs) {
if ($verb.GetType().BaseType.Name -eq 'Array') {
$alias = $verb[1]
$verb = $verb[0]
} else {
$alias = $verb
}
New-Item -Path "Function:\$verb-Something" -Value $FunctionBody
New-Alias -Name $alias -Value "$verb-Something"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment