2

I would like to clear a PowerShell session of mostly all alias definitions, except for common aliases like cd, sort, mkdir, ...
After I finished my session, I would like to restore all previous known the aliases.

There is no need to unload modules or to unregister CmdLets. I just want to clear the alias namespace for my session.

I could specify the allowed aliases in a list like this:

$AllowedAliases = @(
  "cd", "mkdir", "rm", "rmdir",
  "cd", "mkdir", "rm", "rmdir",
  "where", "select",
  "sort"
)

How can I save the aliases and restore them?
or
How can I start a clean PoSh and load only basic aliases?


What I have tested so far:

The following lines are from my example module called poc.psm1.

$Aliases = @()

function Register-PoC
{ foreach ($a in (Get-Item Alias:))
  { $script:Aliases += $a
    Write-Host "$($a.Name) => $($a.ReferencedCommand) ($($a.Visibility))"
    Remove-Item "Alias:$($a.Name)" -Force
  }
}

function Unregister-PoC
{ foreach ($a in $script:Aliases)
  { Write-Host "$($a.Name) <= $($a.ReferencedCommand)"
    if (Test-Path "Alias:$($a.Name)")
    { Write-Host "$($a.Name) exists."      }
    else
    { Set-Alias -Name $a.Name -Value $a.ReferencedCommand -Scope $a.Visibility    }
  }

  if (Test-Path Alias:quit)   {  Remove-Item Alias:quit  }
  Remove-Module PoC
}

Export-ModuleMember -Function 'Register-PoC'
Export-ModuleMember -Function 'Unregister-PoC'

Register-PoC

Set-Alias -Name quit -Value Unregister-PoC     -Description "Unload this module." -Scope Global

Usage example:

Import-Module .\poc.psm1
dir Alias:
quit
dir Alias:

Unfortunately, dir Alias: is not empty after invoking my script...

Another thing is, that I should preserve some settings of these aliases, because manual test showed, that dir does not behave like dir in before:

Remove-Item dir
Set-Alias dir Get-Item
dir
Cmdlet Get-Item an der Befehlspipelineposition 1
Geben Sie Werte für die folgenden Parameter an:
Path[0]:

So dir seams to append a default path to Get-Item if non is set to the alias.

Paebbels
  • 15,573
  • 13
  • 70
  • 139
  • There's a good answer here: https://stackoverflow.com/questions/24914589/how-to-create-permanent-powershell-aliases – intrepidis Nov 16 '17 at 22:33
  • @ChrisNash No this doesn't answer my question. My question is not about aliases. It's about creating an almost empty PowerShell and just allow a handful of commands. – Paebbels Nov 16 '17 at 22:39

2 Answers2

1

Aliases are scoped. When you remove all aliases within a function, the aliases in the global scope aren't affected. Here is code that worked for me (simplifies your code a bit, although I didn't touch unregister-PoC, which could also be simplified I think):

function Register-PoC {
  $script:aliases = get-item alias:
  remove-item alias:* -force
}

function Unregister-PoC
{ foreach ($a in $script:Aliases)
  { Write-Host "$($a.Name) <= $($a.ReferencedCommand)"
    if (Test-Path "Alias:$($a.Name)")
    { Write-Host "$($a.Name) exists."      }
    else
    { Set-Alias -Name $a.Name -Value $a.ReferencedCommand -Scope $a.Visibility    }
  }

  if (Test-Path Alias:quit)   {  Remove-Item Alias:quit  }
  Remove-Module PoC
}

. Register-PoC

Set-Alias -Name quit -Value Unregister-PoC     -Description "Unload this module." -Scope Global

Note the dot operator on Register-PoC. You will need to dot source quit to restore the aliases to global scope.

BTW, rather than the foreach loop in Unregister-PoC you could use copy-item.

Χpẘ
  • 3,403
  • 1
  • 13
  • 22
  • Your solution does not work. I'm testing the code on PS 5.0.10240.16384 (Win10). – Paebbels Jan 20 '16 at 20:16
  • It works on PS 3.0. I don't have 5.0 installed, so can't test it there. Could be a bug (actually by definition it is a bug or a breaking feature change). – Χpẘ Jan 21 '16 at 00:20
  • I tried to start `powershell.exe -Version 4.0` but `$PSVersionTable` always reports 5.0. It's not a 5.0 final ... I'll rest your code on another PC with 4.0 tomorrow. – Paebbels Jan 21 '16 at 00:26
  • 1
    BTW, even if my code doesn't work, the point is the same. Aliases are scoped. If you don't want them at the global scope, you need to delete them at the global scope. Since `remove-item` doesn't provide a scope parameter your only other (documented) choice is to use dot sourcing. – Χpẘ Jan 21 '16 at 00:31
1

For your situation, I would recommend using PowerShell profiles. These can be defined per user, per machine, and other situations. You can automatically run functions stored in the profile just by calling the function after it's defined in the profile.

For just your current user on the current machine, see Example 3 here.

New-Item -Path $PROFILE -ItemType File -Force

For other profile options, check out Understanding the Six PowerShell Profiles.

To ignore a profile, you can do that by directly running powershell.exe -NoProfile -NoExit but beware of nested sessions when doing that in another PowerShell session.

For a way to wipe all aliases except your desired list, you can export the aliases and re-import them after wiping all aliases. This can be added to the profile, if desired. Otherwise assign it to a function in the profile and call as needed. Change path if not using the profile folder(or wherever you like to keep things):

$allowedaliases = "cd","dir","rm","rmdir","where","select","sort"
Export-Alias -Path "$((Get-ChildItem $PROFILE).DirectoryName)\aliases.csv" -Name $allowedaliases
Remove-Item Alias:* -Force
Import-Alias -Path "$((Get-ChildItem $PROFILE).DirectoryName)\aliases.csv" -Force

Note: One of the original listed aliases(mkdir) is a function, not an alias, at least in Powershell v5.0. Also added dir into the list since that was mentioned by the OP.

Booga Roo
  • 1,665
  • 1
  • 21
  • 30
  • Loading powershell.exe with `-NoProfile` does not provide an empty alias list. – Paebbels Jan 20 '16 at 20:23
  • Correct. It doesn't load aliases defined in a profile and leaves the default aliases intact. It's a way to "undo" any aliases created in a profile and start with a "clean" slate. It's only a partial solution if you're looking to completely wipe out even the default aliases, but is one way to manage user-defined aliases and variables. – Booga Roo Jan 20 '16 at 20:53
  • I was also looking for a solution to remove aliases like ipmo. – Paebbels Jan 20 '16 at 21:52
  • @Paebbels Updated answer based on desired results. – Booga Roo Jan 20 '16 at 23:17