Create aliases in windows

Alias in Windows and it’s Fun Applications using Python

I was wondering how could I possibly get a python script to run automatically every time I open the command-line. I believe that it could have some fun applications.

I imagined opening up the command-line and writing

todo “Learn Ableton Live 10”

to add “Learn Ableton Live 10” to a To-Do List (.txt file).

But how could I pull this off? I mean, obviously, the command-line does not recognize ‘todo’ command and how would I call a python script by hitting ‘todo’ anyway…

This is where ‘Alias’ comes into the picture!

What is an Alias?

An alias, as the name refers provides an alternate name for existing names. Alias is usually an easier-to-understand name for a defined data object.

For you to understand the idea of alias, I am going to say that “sup” is an alias to “wassup” which itself is an alias to “what’s up” 😛

So we are basically talking about making our own lingos in programming. Doesn’t it sound cool already? 😎

How is Aliasing Useful?

If you type ‘cls’ in a Windows command-line or ‘clear’ in Linux terminal and hit enter, it clears everything out from there. We could make an alias ‘c’ just to perform the same task.

Also, we often have a directory which we frequently have to visit via the terminal by using the ‘cd’ command. It becomes very frustrating to use the ‘cd’ command every time we open a new terminal to enter into that directory, especially when the directory has a very long path. This is another appropriate use case of setting up an alias.

And similarly, we can make aliases for various different commands that are valid for a command-line.

How to Create an Alias in Windows?

Let’s now learn how to create an alias. Belonging to an intelligent species, you might have already figured out how to create an alias, after seeing the 2 examples that I used earlier.

You got that correct!

We use ‘doskey’ command to create an alias. We write ‘doskey’, then the alias name followed by the equal to sign (‘=’ ) further followed by the command that the alias is supposed to run.

How to Call an Alias?

Once we are done creating the alias, calling them is as simple as typing the name of the alias and hitting the enter key in the command-line!

Let’s see the alias ‘teleport’ that we created earlier in action now.

Creating an Alias for a Python Program?

Now that we know how to create an alias, it seems pretty straightforward to figure out the way how we can create an alias for calling a python script.

We use the ‘doskey’ command and assign the command for running a specific python script, to an alias using the equal to sign (‘=’).

Here my alias named “todo” is supposed to run the python script called “todo_list_maker.py” which is located at “C:/Users/anime/Documents/Python Scripts/todo_list_maker/”.

The python script “todo_list_maker.py” takes an input (a to-do list item) from the command-line and puts it in a todo_list.txt

But how do we pass in the arguments to our python script?

It is actually quite simple. All we need to do is add a dollar sign and an asterisk (“$*”) at the end of the alias assigning step in the way it is mentioned down below. It allows the inputs to the python script to be passed while calling the alias.

I have used argparser for parsing the arguments from the command-line in todo_list_maker.py

Mentioned below is the python script ‘todo_list_maker.py’

And following is the command that we need to use in the command-line to call the alias “todo” and add a to-do list item in the to-do list.

Читайте также:  Windows wasapi что это

And as expected it generates a to-do list (.txt file) on the Desktop (by default)

and adds the to-do list item in it.

So this is how we create an alias for calling a python script and pass arguments in it through the alias.

But there is a last piece of information that I would like to add in this blog. The aliases do not work when we try to call them in a new command-line. This can be fixed by making a Batch or BAT file (.bat file) which would hold the command(s) that would run every time a new command-line terminal is opened.

In Windows, the batch file is a file that stores commands in a serial order. Command-line interpreter takes the file as an input and executes the stored commands in the same order. A batch file is simply a text file saved with the .bat file extension. It can be written using Notepad or any other text editor.

So we make a BAT file and save it at any location on the computer (Note this location as you would be using this location in a short while). Following is the BAT file that I made. It will first execute the “echo” command and then then the “doskey” command, each and every time a new command-line is opened.

Now we go to the Windows Search option and type “cmd” and then click on “Open file location” option.

We then right-click on the “Command Prompt” icon and select the “Properties” option.

Then we select the “Shortcut” tab and add

“/k C:\Users\anime\doskey_for_python.bat” (/k path_of _the _bat_file) in the “Target” field.

Hit “Apply” and ‘OK’ and we are done.

Now every time we open a new command-line, the BAT file is executed and our alias is ready to be used. This holds true even after we restart the computer which is exactly how we would want it to be.

So finally our “todo” command is ready to be used in the command-line to add new to-do list items in the to-do list.

We can now combine the idea of alias with the infinite functionalities that python brings to the table, to make fun commands do useful tasks!

You can find the code for this “todo list maker” application on my GitHub account by clicking on this link https://github.com/n0obcoder/fun-with-python/tree/master/todo_list_maker

The README.md file provides a decent documentation of the todo_list_maker.py. Please feel free to explore it and add more functionalities to it 🙂

I am writing this blog because I have learned a lot by reading other’s blogs and I feel that I should also write and share my learnings and knowledge, as much as I can. So please leave your feedback in the comments section below to let me know how can I improve my future blogs! 😀

Create aliases in windows

В процессе работы web-программисту часто приходится пользоваться командной строкой. Это может быть работа с git, установка библиотек через npm или commposer. Создание шаблона приложения. Очистка кэша web-приложения. Управление миграциями базы данных и т.д.

В таком случае могут возникнуть 2 проблемы. Во-первых нужно постоянно печатать повторяющиеся команды. Либо копировать откуда-то. Во вторых нужно помнить эти самые команды. Что тоже бывает сложно. Например команда создания миграции в symfony 3 выглядит так.

В какой-то момент это все надоедает и хочется создать сокращения для команд. Под Windows можно сделать с помощью doskey.

Alias можно создать такой командой. Однако это работает только для текущей сессии.

Если хочется создать много алиасов, имеет смысл создать .bat файл и записать туда все алиасы. Сохранить файл в удобном месте, например так:

Далее нужно сделать так, чтобы все это применялось автоматически при старте системы. Для этого нужно зайти в редактор реестра, выполнив команду regedit.

Далее найти ключ HKEY_CURRENT_USER\Software\Microsoft\Command Processor\Autorun и установить путь к .bat файлу.

Все, можно пользоваться алиасами. Мой список alias выглядит так:

Список включает в себя наиболее частоиспользуемые команды git, команды yii, symfony. Также некоторые команды для работы с mysql. Список обновляется по мере использования мною новых технологий, фреймворков и т.д.

Если нужно добавить сложную составную команду, рекомендую вынести ее в отдельный .bat файл и сделать алиас на него.

Проверено на windows 10. Спасибо за внимание!

Set-Alias

Creates or changes an alias for a cmdlet or other command in the current PowerShell session.

Syntax

Description

The Set-Alias cmdlet creates or changes an alias for a cmdlet or a command, such as a function, script, file, or other executable. An alias is an alternate name that refers to a cmdlet or command. For example, sal is the alias for the Set-Alias cmdlet. For more information, see about_Aliases.

Читайте также:  Обход starforce windows 10

A cmdlet can have multiple aliases, but an alias can only be associated with one cmdlet. You can use Set-Alias to reassign an existing alias to another cmdlet, or change an alias’s properties, such as the description.

An alias that is created or changed by Set-Alias is not permanent and is only available during the current PowerShell session. When the PowerShell session is closed, the alias is removed.

Examples

Example 1: Create an alias for a cmdlet

This command creates an alias to a cmdlet in the current PowerShell session.

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name parameter specifies the alias’s name, list . The Value parameter specifies the cmdlet that the alias runs.

To run the alias, type list on the PowerShell command line.

Example 2: Reassign an existing alias to a different cmdlet

This command reassigns an existing alias to run a different cmdlet.

The Get-Alias cmdlet uses the Name parameter to display the list alias. The list alias is associated with the Get-ChildItem cmdlet. When the list alias is run, the items in the current directory are displayed.

The Set-Alias cmdlet uses the Name parameter to specify the list alias. The Value parameter associates the alias to the Get-Location cmdlet.

The Get-Alias cmdlet uses the Name parameter to display the list alias. The list alias is associated with the Get-Location cmdlet. When the list alias is run, the current directory’s location is displayed.

Example 3: Create and change a read-only alias

This command creates a read-only alias. The read-only option prevents unintended changes to an alias. To change or delete a read-only alias, use the Force parameter.

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name parameter specifies the alias’s name, loc . The Value parameter specifies the Get-Location cmdlet that the alias runs. The Option parameter specifies the ReadOnly value. The PassThru parameter represents the alias object and sends the object down the pipeline to the Format-List cmdlet. Format-List uses the Property parameter with an asterisk ( * ) so that all of the properties are displayed. The example output shows a partial list of those properties.

The loc alias is changed with the addition of two parameters. Description adds text to explain the alias’s purpose. The Force parameter is needed because the loc alias is read-only. If the Force parameter is not used, the change fails.

Example 4: Create an alias to an executable file

This example creates an alias to an executable file on the local computer.

The Set-Alias cmdlet creates an alias in the current PowerShell session. The Name parameter specifies the alias’s name, np . The Value parameter specifies the path and application name C:\Windows\notepad.exe. The Get-Alias cmdlet uses the Name parameter to show that the np alias is associated with notepad.exe.

To run the alias, type np on the PowerShell command line to open notepad.exe.

Example 5: Create an alias for a command with parameters

This example shows how to assign an alias to a command with parameters.

You can create an alias for a cmdlet, such as Set-Location . You cannot create an alias for a command with parameters and values, such as Set-Location -Path C:\Windows\System32 . To create an alias for a command, create a function that includes the command, and then create an alias to the function. For more information, see about_Functions.

A function named CD32 is created. The function uses the Set-Location cmdlet with the Path parameter to specify the directory, C:\Windows\System32 .

The Set-Alias cmdlet creates an alias to the function in the current PowerShell session. The Name parameter specifies the alias’s name, Go . The Value parameter specifies the function’s name, CD32 .

To run the alias, type Go on the PowerShell command line. The CD32 function runs and changes to the directory C:\Windows\System32 .

Example 6: Update options for an existing alias

This example shows how to assign multiple options using the Option parameter.

Using the example above we will set the alias Go as ReadOnly and Private .

Читайте также:  Intel stick stk1aw32sc windows 10 64 bit

The alias Go should already exist. After running the command above, the alias is not be able to be changed without using the Force parameter and is only available in the current scope.

Parameters

Prompts you for confirmation before running the cmdlet.

Type: SwitchParameter
Aliases: cf
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

Specifies a description of the alias. You can type any string. If the description includes spaces, enclose it single quotation marks.

Type: String
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Use the Force parameter to change or delete an alias that has the Option parameter set to ReadOnly.

The Force parameter cannot change or delete an alias with the Option parameter set to Constant.

Type: SwitchParameter
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

Specifies the name of a new alias. An alias name can contain alphanumeric characters and hyphens. Alias names cannot be numeric, such as 123.

Type: String
Position: 0
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Sets the Option property value of the alias. Values such as ReadOnly and Constant protect an alias from unintended changes. To see the Option property of all aliases in the session, type Get-Alias | Format-Table -Property Name, Options -Autosize .

The acceptable values for this parameter are as follows:

  • AllScope — The alias is copied to any new scopes that are created.
  • Constant — Cannot be changed or deleted.
  • None — Sets no options and is the default.
  • Private — The alias is available only in the current scope.
  • ReadOnly — Cannot be changed or deleted unless the Force parameter is used.
  • Unspecified

These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the Option parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values.

Type: ScopedItemOptions
Accepted values: AllScope, Constant, None, Private, ReadOnly, Unspecified
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Returns an object that represents the alias. Use a format cmdlet such as Format-List to display the object. By default, Set-Alias does not generate any output.

Type: SwitchParameter
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False

Specifies the scope in which this alias is valid. The default value is Local. For more information, see about_Scopes.

The acceptable values are as follows:

  • Global
  • Local
  • Private
  • Numbered scopes
  • Script
Type: String
Accepted values: Global, Local, Private, Numbered scopes, Script
Position: Named
Default value: Local
Accept pipeline input: False
Accept wildcard characters: False

Specifies the name of the cmdlet or command that the alias runs. The Value parameter is the alias’s Definition property.

Type: String
Position: 1
Default value: None
Accept pipeline input: True
Accept wildcard characters: False

Shows what would happen if the cmdlet runs. The cmdlet is not run.

Type: SwitchParameter
Aliases: wi
Position: Named
Default value: False
Accept pipeline input: False
Accept wildcard characters: False

Inputs

None

Set-Alias does not accept input from the pipeline.

Outputs

None or System.Management.Automation.AliasInfo

When you use the PassThru parameter, Set-Alias generates a System.Management.Automation.AliasInfo object representing the alias. Otherwise, Set-Alias does not generate any output.

Notes

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. Remove-Item is accepted for backwards compatibility such as for scripts created with prior versions of PowerShell. Use a command such as Remove-Item -Path Alias:aliasname .

To create an alias that is available in each PowerShell session, add it to your PowerShell profile. For more information, see about_Profiles.

An alias can be saved and reused in another PowerShell session by doing an export and import. To save an alias to a file, use Export-Alias . To add a saved alias to a new PowerShell session, use Import-Alias .

Оцените статью