Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restoring a PowerShell alias when a module is unloaded

Tags:

powershell

How do I restore a PowerShell alias when my module has been unloaded.

The code I have so far does not work although executing the Set-Alias command by itself does. It stores the definition in a local variable, which is available when the OnRemove event is fired.

$orig_cd = (Get-Alias -Name 'cd').Definition
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
    Set-Alias -Name 'cd' -Value $orig_cd -Force -Option AllScope -Scope Global
}

I should also mention that I am overriding the existing cd command alias like so

Set-Alias -Name cd -Value cdX -Force -Option AllScope -Scope Global

Here is the source code to the module https://github.com/vincpa/z/blob/master/z.psm1

Update

Adding a Write-Host command within the OnRemove handler shows that the value of $orig_cd is indeed Set-Location.

like image 834
Razor Avatar asked Jun 29 '14 11:06

Razor


2 Answers

I tried this, and it works:

$orig_cd = (Get-Alias -Name 'cd').Definition
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
    set-item alias:cd -value $orig_cd
}

Set-item alias:cd -Value 'cdX'

Also, a suggestion - you are writing a module which people will use in their terminals. I don't expect a use case where some one would want to remove your module. These steps maybe overkill for the module you are writing.

like image 189
manojlds Avatar answered Oct 25 '22 21:10

manojlds


Although about_scopes is a bit confusing, the Alias Provider looks like it has the key.

The alias is already scoped with AllScope which means children scope have copies/access. All you have to do is change the value.

Look at the switch -Options in Set-Alias - http://technet.microsoft.com/en-us/library/hh849938.aspx

-- AllScope: The alias is copied to any new scopes that are created.

#Override the existing CD command with the wrapper in order to log 'cd' commands.
Set-Item alias:cd -Value 'cdx'
Set-Alias -Name pushd -Value pushdX -Force -Option AllScope -Scope Global

$orig_cd = (Get-Alias -Name 'cd')
$MyInvocation.MyCommand.ScriptBlock.Module.OnRemove = {
    set-item alias:cd -value 'set-content'
}

Export-ModuleMember -Function z, cdX, pushdX -alias ''
like image 38
Jaigene Kang Avatar answered Oct 25 '22 21:10

Jaigene Kang