Windows powershell linux команды

Integrate Linux Commands into Windows with PowerShell and the Windows Subsystem for Linux

September 26th, 2019

A common question Windows developers have is “why doesn’t Windows have yet?”. Whether longing for a powerful pager like less or wanting to use familiar commands like grep or sed , Windows developers desire easy access to these commands as part of their core workflow.

The Windows Subsystem for Linux (WSL) was a huge step forward here, enabling developers to call through to Linux commands from Windows by proxying them through wsl.exe (e.g. wsl ls ). While a significant improvement, the experience is lacking in several ways:

  • Prefixing commands with wsl is tedious and unnatural
  • Windows paths passed as arguments don’t often resolve due to backslashes being interpreted as escape characters rather than directory separators
  • Windows paths passed as arguments don’t often resolve due to not being translated to the appropriate mount point within WSL
  • Default parameters defined in WSL login profiles with aliases and environment variables aren’t honored
  • Linux path completion is not supported
  • Command completion is not supported
  • Argument completion is not supported

The result of these shortcomings is that Linux commands feel like second-class citizens to Windows and are harder to use than they should be. For a command to feel like a native Windows command, we’ll need to address these issues.

PowerShell Function Wrappers

We can remove the need to prefix commands with wsl , handle the translation of Windows paths to WSL paths, and support command completion with PowerShell function wrappers. The basic requirements of the wrappers are:

  • There should be one function wrapper per Linux command with the same name as the command
  • The wrapper should recognize Windows paths passed as arguments and translate them to WSL paths
  • The wrapper should invoke wsl with the corresponding Linux command, piping in any pipeline input and passing on any command line arguments passed to the function

Since this template can be applied to any command, we can abstract the definition of these wrappers and generate them dynamically from a list of commands to import.

The $command list defines the commands to import. Then we dynamically generate the function wrapper for each using the Invoke-Expression command (first removing any aliases that would conflict with the function).

The function loops through the command line arguments, identifies Windows paths using the Split-Path and Test-Path commands, then converts those paths to WSL paths. We run the paths through a helper function we’ll define later called Format-WslArgument that escapes special characters like spaces and parentheses that would otherwise be misinterpreted.

Finally, we pass on pipeline input and any command line arguments through to wsl .

With these function wrappers in place, we can now call our favorite Linux commands in a more natural way without having to prefix them with wsl or worry about how Windows paths are translated to WSL paths:

  • man bash
  • less -i $profile.CurrentUserAllHosts
  • ls -Al C:\Windows\ | less
  • grep -Ein error *.log
  • tail -f *.log
Читайте также:  Лучшие антивирусы для windows server

A starter set of commands is shown here, but you can generate a wrapper for any Linux command simply by adding it to the list. If you add this code to your PowerShell profile, these commands will be available to you in every PowerShell session just like native commands!

Default Parameters

It is common in Linux to define aliases and/or environment variables within login profiles to set default parameters for commands you use frequently (e.g. alias ls=ls -AFh or export LESS=-i ). One of the drawbacks of proxying through a non-interactive shell via wsl.exe is that login profiles are not loaded, so these default parameters are not available (i.e. ls within WSL and wsl ls would behave differently with the alias defined above).

PowerShell provides $PSDefaultParameterValues , a standard mechanism to define default parameter values, but only for cmdlets and advanced functions. Turning our function wrappers into advanced functions is possible but introduces complications (e.g. PowerShell matches partial parameter names (like matching -a for -ArgumentList ) which will conflict with Linux commands that accept the partial names as arguments), and the syntax for defining default values would be less than ideal for this scenario (requiring the name of a parameter in the key for defining the default arguments as opposed to just the command name).

With a small change to our function wrappers, we can introduce a model similar to $PSDefaultParameterValues and enable default parameters for Linux commands!

By passing $WslDefaultParameterValues down into the command line we send through wsl.exe , you can now add statements like below to your PowerShell profile to configure default parameters!

Since this is modeled after $PSDefaultParameterValues , you can temporarily disable them easily by setting the «Disabled» key to $true . A separate hash table has the additional benefit of being able to disable $WslDefaultParameterValues separately from $PSDefaultParameterValues .

Argument Completion

PowerShell allows you to register argument completers with the Register-ArgumentCompleter command. Bash has powerful programmable completion facilities. WSL lets you call into bash from PowerShell. If we can register argument completers for our PowerShell function wrappers and call through to bash to generate the completions, we can get rich argument completion with the same fidelity as within bash itself!

The code is a bit dense without an understanding of some bash internals, but basically:

  • We register the argument completer for all of our function wrappers by passing the $commands list to the -CommandName parameter of Register-ArgumentCompleter
  • We map each command to the shell function bash uses to complete for it ( $F which is named after complete -F used to define completion specs in bash)
  • We convert PowerShell’s $wordToComplete , $commandAst , and $cursorPosition arguments into the format expected by bash completion functions per the bash programmable completion spec
  • We build a command line that we can pass to wsl.exe that ensures the completion environment is set up correctly, invokes the appropriate completion function, then outputs a string containing the completion results separated by new lines
  • We then invoke wsl with the command line, split the output string on the new line separator, then generate CompletionResults for each, sorting them, and escaping characters like spaces and parentheses that would otherwise be misinterpreted
Читайте также:  Windows boot setting что это

The end result of this is now our Linux command wrappers will use the exact same completion that bash uses! For example:

Each completion will provide values specific to the argument before it, reading in configuration data like known hosts from within WSL!

will cycle through options. will show all available options.

Additionally, since bash completion is now in charge, you can resolve Linux paths directly within PowerShell!

In cases where bash completion doesn’t return any results, PowerShell falls back to its default completion which will resolve Windows paths, effectively enabling you to resolve both Linux paths and Windows paths at will.

Conclusion

With PowerShell and WSL, we can integrate Linux commands into Windows just as if they were native applications. No need to hunt around for Win32 builds of Linux utilities or be forced to interrupt your workflow to drop into a Linux shell. Just install WSL, set up your PowerShell profile, and list the commands you want to import! The rich argument completion shown here of both command options and Linux and Windows file paths is an experience even native Windows commands don’t provide today.

The complete source code described above as well as additional guidance for incorporating it into your workflow is available at https://github.com/mikebattista/PowerShell-WSL-Interop.

Which Linux commands do you find most useful? What other parts of your developer workflow do you find lacking on Windows?

Let us know in the comments below or over on GitHub!

Источник

Работа с Powershell Linux

После того как компания Microsoft заинтересовалась Linux и открыла исходный код нескольких своих проектов, был открыт код командного интерпретатора и оболочки для выполнения системных скриптов Windows — PowerShell. Раньше PowerShell была доступна только для Windows, но теперь ее можно использовать даже в Linux и MacOS.

В этой статье мы рассмотрим что такое PowerShell, чем она может быть нам полезна, а также как выполняется работа с PowerShell Linux.

Что такое PowerShell?

PowerShell — это больше чем командная оболочка, это система автоматизации задач и управления конфигурацией, разработанная в Microsoft. Она состоит из интерпретатора команд (оболочки) и языка сценариев, основанного на платформе NET Framework. PowerShell реализует полный доступ к COM (Component Object Model) и WMI (Windows Management Instrumentation), поэтому позволяет системным администраторам выполнять различные административные действия на локальной или удаленных машинах. Также поддерживаются технологии WS-Management и CIM (Common Information Model), что позволяет управлять сетевыми устройствами.

Для решения каждой возникшей задачи необходимо создавать .NET классы, которые называются cmdlet или по-нашему коммандлеты. Для создания скриптов, так же как и в Linux можно сохранять группы коммандлетов в файл. Затем эти скрипты можно применить в качестве утилит командной строки или дополнительных инструментов.

Установка PowerShell в Linux

В официальных репозиториях оболочки PowerShell, к сожалению, нет, но в Microsoft создали свой PPA репозиторий, который мы можем использовать. Для добавления репозитория в Ubuntu используйте такие команды:

curl https://packages.microsoft.com/keys/microsoft.asc |sudo apt-key add —
$ curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list |sudo tee /etc/apt/sources.list.d/microsoft.list
$ sudo apt-get update

Читайте также:  Arduino driver windows downloads

Эти команды рассчитаны на Ubuntu 16.04, для добавления репозитория в Ubuntu 16.10 используйте такие команды:

curl https://packages.microsoft.com/keys/microsoft.asc |sudo apt-key add —
$ curl https://packages.microsoft.com/config/ubuntu/16.10/prod.list |sudo tee /etc/apt/sources.list.d/microsoft.list
$ sudo apt-get update

Затем используйте пакетный менеджер apt для установки powershell и необходимых компонентов:

sudo apt install -y powershell

Для Red Hat, Fedora и CentOS Microsft тоже подготовили отдельный репозиторий. Чтобы его добавить выполните:

sudo curl https://packages.microsoft.com/config/rhel/7/prod.repo> /etc/yum.repos.d/microsoft.repo

Затем используйте yum для установки:

sudo yum install -y powershell

Работа с PowerShell в Linux

После того как установка PowerShell Linux будет завершена, вы можете перейти к работе с этой оболочкой. Дальше мы рассмотрим как начать работать, разберем основные команды для работы с файлами, каталогами и процессами. Также рассмотрим как получить список всех доступных команд и справку по них.

Чтобы запустить сеанс PowerShell выполните такую команду:

Теперь, вы можете узнать версию PowerShell и ее компонентов с помощью такой команды:

Продолжим рассмотрение команд, с команд для получения информации. Следующие две команды позволяют узнать текущую дату и время бесперебойной работы компьютера:

А эта команда позволяет узнать текущую рабочую папку:

Работа с файлами в PowerShell

Чтобы создать новый пустой файл используйте команду:

Затем добавим в этот файл содержимое:

> set-content losst.txt -value «Linux Open Source Software Technologies»

И смотрим новое содержимое файла:

Чтобы удалить файл используйте команду remove-item:

> remove-item losst.txt
> get-content losst.txt

Создайте новый каталог и перейдите в него:

> mkdir losst-files
> cd losst-files

Затем создадим один файл в этой папке и посмотрим ее содержимое:

> new-item losst.txt
> ls

Если вы хотите получить полный список файлов в папке с подробной информацией используйте команду dir:

Работа с процессами в PowerShell

Чтобы посмотреть список запущенных процессов используйте команду get-process:

Также вы можете получить информацию только по определенному процессу или группе, для этого передайте его имя в параметрах команде:

Вот значения основных колонок, которые выводит команда:

  • NPM (K) — количество оперативной памяти, которую процесс использует в килобайтах;
  • PM(K) — количество выгружаемой оперативной памяти, используемой процессом в килобайтах;
  • WS (K) — размер блока с исполняемыми инструкциями процесса в килобайтах;
  • CPU(s) — занимаемый процент процессорного времени;
  • ID — идентификатор процесса (PID);
  • ProcessName — имя процесса.

Как видите, здесь можно увидеть всю основную информацию о процессах. Чтобы остановить процесс используйте команду stop-process, в параметрах ей нужно передать PID:

> get-process ping
> stop-process 29895

Информация про PowerShell

Вы можете узнать всю необходимую информацию про команды PowerShell Linux, чтобы работа с оболочкой была максимально удобной. Для просмотра информации про доступные команды:

Чтобы посмотреть более подробную информацию по нужной команде используйте функцию get-help. Например, узнаем информацию про команду Describe:

Чтобы посмотреть все доступные псевдонимы команд используйте:

И еще одна вещь, которая может вам понадобиться, это история команд. Для ее просмотра наберите:

Выводы

Вот и все. В этой статье мы показали как выполняется работа с PowerShell Linux, а также как установить эту оболочку во всех основных дистрибутивах. PowerShell очень сильно отличается от привычных оболочек Linux, которые имеют лучшие, продуктивные и более интересные команды для выполнения различных задач из командной строки или написания скриптов. Но, возможно, администраторам Windows будет интересно использовать именно эту оболочку.

Источник

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