Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to create a PowerShell alias in a script module

Tags:

powershell

Steps to reproduce:

Create a TestAlias module in \WindowsPowerShell\Modules\TestAlias\TestAlias.psm1 with the following function and alias:

function foo
{ write-output 'foo' }


New-Alias -name bar -value foo

From a PowerShell session:

import-module TestAlias
bar

The term 'bar' is not recognized as the name of a cmdlet, function, script file, or operable program...

like image 579
Chad Miller Avatar asked Dec 30 '09 04:12

Chad Miller


People also ask

How do I create an alias in PowerShell?

PowerShell includes built-in aliases that are available in each PowerShell session. The Get-Alias cmdlet displays the aliases available in a PowerShell session. To create an alias, use the cmdlets Set-Alias or New-Alias . In PowerShell 6, to delete an alias, use the Remove-Alias cmdlet.

How do I add an alias to my PowerShell profile?

To create an alias for a command, create a function that includes the command, and then create an alias to the function. To save the aliases from a session and use them in a different session, add the Set-Alias * command to your Windows PowerShell profile.

What is the cmdlet used to create alias?

The New-Alias cmdlet creates a new alias in the current PowerShell session. Aliases created by using New-Alias are not saved after you exit the session or close PowerShell. You can use the Export-Alias cmdlet to save your alias information to a file.


1 Answers

You can use

Export-ModuleMember -Function * -Alias * 

to export all functions and aliases.

By default, Windows PowerShell modules only export commands (functions or cmdletS), and not variables or aliases.

I'll go into a little more detail about why this is.

The short answers is that aliases, while convenient when writing one liners, are a barrier to understanding a script or a module. They are icing on the cake of a good cmdlet, but the core thing to expose is the good cmdlet. Aliases make it more difficult for a user reading your script to figure out what you're trying to do (Set-Content is a lot easier to understand than sc). Variables can be even worse to expose, as they can easily be set to unexpected values and as there is very little to help a user of your module figure out that they are there. Because commands are easily discoverable (Get-Command -Module FOO) and easier to explore (with Get-Help), the default that a module will export is only commands. As with most other things in PowerShell, you can override it if you choose, but by default commands are the only thing that are exported from a module.

Hope this Helps

like image 155
Start-Automating Avatar answered Oct 13 '22 14:10

Start-Automating