|
| 1 | +function Set-Function { |
| 2 | + <# |
| 3 | + .SYNOPSIS |
| 4 | + Create a PowerShell function |
| 5 | +
|
| 6 | + .DESCRIPTION |
| 7 | + This is useful if you want to create a function where the name |
| 8 | + is given by an arbitrary string expression. |
| 9 | +
|
| 10 | + When defining a function with the PowerShell "Function" keyword |
| 11 | + then a fixed name has to be given. |
| 12 | +
|
| 13 | + .PARAMETER RemoveAlias |
| 14 | + If an alias exists with the given name, remove it. This is neccessary because |
| 15 | + aliases have higher precedence than functions. |
| 16 | +
|
| 17 | + .EXAMPLE |
| 18 | + Set-Function "${funname}-asdf" {Write-Output "Hello World"} |
| 19 | +
|
| 20 | + .EXAMPLE |
| 21 | + Set-Function "existingfunction" {Write-Output "new implementation"} -Confirm |
| 22 | + #> |
| 23 | + [CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')] |
| 24 | + param( |
| 25 | + [Parameter(Mandatory)] [String] $Name, |
| 26 | + [Parameter(Mandatory)] [ScriptBlock] $Implementation, |
| 27 | + [Switch] $NoRemoveAlias |
| 28 | + ) |
| 29 | + |
| 30 | + # Check if the function already exists |
| 31 | + if (Test-Path "Function:$Name") { |
| 32 | + if ($PSCmdlet.ShouldProcess("Function:$Name", 'Overwrite the function.')) { |
| 33 | + Remove-Item -Path "Function:$Name" -Confirm:$false |
| 34 | + } else { |
| 35 | + return |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + # Check if an alias with this name exists |
| 40 | + if ((-not $NoRemoveAlias) -and (Test-Path "Alias:$Name")) { |
| 41 | + if ($PSCmdlet.ShouldProcess("Alias:$Name", 'Remove the alias.')) { |
| 42 | + Remove-Item "Alias:$Name" -Force -Confirm:$False |
| 43 | + |
| 44 | + # We need to run this a second time because if a local alias exists |
| 45 | + # inside the function scope then the first time we only remove |
| 46 | + # the local alias, the second time the global alias is removed. |
| 47 | + if (Test-Path "Alias:$Name") {Remove-Item "Alias:$Name" -Force} |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + New-Item -Path "Function:global:$Name" -Value $Implementation -Confirm:$False | Out-Null |
| 52 | +} |
0 commit comments