How to create a Powershell Alias for Set-Executionpolicy

Viewed 102

Following guides to create an alias in powershell, I have run the following command:

Set-Alias rush-enable "Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass"

This sets the alias. However when I run the alias I hit an error.

PS C:\example> rush-enable                
rush-enable : The term 'Set-ExecutionPolicy -Scope Process       
-ExecutionPolicy Unrestricted' is not recognized as the name of  
a cmdlet, function, script file, or operable program. Check the  
spelling of the name, or if a path was included, verify that     
the path is correct and try again.
At line:1 char:1
+ rush-enable
+ ~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Set-ExecutionPo.  
   ..cy Unrestricted:String) [], CommandNotFoundException        
    + FullyQualifiedErrorId : CommandNotFoundException

However running the command on it's own works fine:

PS C:\example> Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted
PS C:\example> 

Am I missing something? How should I format the command to work as an alias?

1 Answers

As per the documentation:

You can assign an alias to a cmdlet, script, function, or executable file.

You cannot assign an alias to a command and its parameters. For example, you can assign an alias to the Get-Eventlog cmdlet, but you cannot assign an alias to the Get-Eventlog -LogName System command.

This is presumably a way to avoid having to disambiguate a parameter that exists on an alias and which is passed when invoking the alias.

You therefore have two options:

  1. Encapsulate your command in a function called Enable-Rush (note the PowerShell acceptable naming scheme, if you care). In your case this would look something like:
function Enable-Rush {
    Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
}
  1. Save the command as a file and create a alias to the file.

And to persist it, put it in a $PROFILE. Depending on your system, you might need to digitally sign the $PROFILE or change the PowerShell system Execution Policy to allow PowerShell scripts generated by the system to execute when starting a PowerShell process.

Related