В чем отличие windows powershell от windows powershell ise

PowerShell is a command line interface tool, whereas PowerShell ISE is a GUI based application and comes with many advanced features.

Download PC Repair Tool to quickly find & fix Windows errors automatically

A Shell is a program that uses the command line interface or graphical user interface and allows users to access and control their computers by entering commands. The program is named Shell because it is the outermost layer of an operating system. The shell acts as a communication medium between a user and an operating system.

PowerShell is a command-line and scripting tool in Windows 10. It is developed by Microsoft Corporation and is used for the automation of tasks and configuration management. PowerShell ISE is another tool developed by Microsoft Corporation which is used for creating, running, and debugging commands and scripts. In PowerShell ISE, ISE stands for Integrated Scripting Environment. Hence, PowerShell ISE also comprises some advanced features that Windows PowerShell does not have.

PowerShell Vs PowerShell ISE

While PowerShell uses a command-line interface (CLI), PowerShell ISE uses a graphical user interface (GUI). Because GUI is easy to use and understand, users can execute and debug commands and scripts without writing all the commands in the command-line interface. Apart from this, there are several more features that make PowerShell ISE more advanced than PowerShell. This article illustrates the difference between Windows PowerShell and Windows PowerShell ISE.

What is PowerShell ISE?

As described above in this post, PowerShell ISE is a GUI-based application that lets users run and debug commands and scripts.

Let’s see the features of PowerShell ISE:

  • Multiline editing: By using this feature, you can insert an empty line under the current line in the Command Pane. To use the Multiline editing feature, you have to press the Shift  + Enter keys on your keyboard.
  • Selective execution: This feature lets you run a part of a script by selecting the text. After selecting the text, you simply have to click on the Run Script button. The F5 key is the shortcut to this feature.
  • Context-sensitive help: It opens a help file. To use this feature, type Invoke-Item and then press the F1 key.

Read: Windows Terminal Tips and Tricks.

We will compare these tools based on the following properties/features:

  1. User-interface
  2. Tasks
  3. Editing the commands and scripts
  4. Context-sensitive Help
  5. Command Add-ons

1] User-interface

We have described above in this article that PowerShell has a command-line interface, whereas the PowerShell ISE comes with a graphical user interface. Due to this, PowerShell offers a user-friendly interface and is easy to use and understand for beginners.

If you compare the interface of both of these tools, you will find that PowerShell ISE comes with an attractive interface with a toolbar, menu bar, script pane, console pane, multiple tabs feature, etc.

2] Tasks

Because you can open multiple tabs in PowerShell ISE, it is a multitasking tool. You can run multiple commands and scripts in PowerShell ISE in different tabs. This feature is not available in PowerShell.

TIP: Posterpedia is a cool Microsoft Store app that will help you understand Microsoft technologies.

3] Editing commands and scripts

Editing a script in PowerShell ISE is easy as it comes with a number of tools that you can use for editing. If you click on the Edit menu, you will see the following features:

  • Find in script
  • Find next in script
  • Find previous in script
  • Replace in script
  • Go to line
  • Go to match

These features save your time by making the script editing process hassle-free. On the other hand, the Edit menu is not available in PowerShell, which makes the script editing process a bit time-consuming in case the script is long.

Read: How to Install and Use Windows PowerShell ISE.

4] Context-sensitive help

The context-sensitive help feature is not available in PowerShell.

Read: Terminal vs PowerShell vs Command Prompt difference explained

5] Commands Add-ons

In PowerShell ISE, a command add-ons panel is available on the right side of the interface. You can search for a particular command and insert it into the Console Pane by clicking on the Insert button. You can also filter the commands by clicking on the drop-down menu.

Such a type of panel is not available in PowerShell.

That’s it.

Related reads:

  • PowerShell opens at Startup.
  • How to disable PowerShell.

Ezoic

Nishant is a tech enthusiast who loves writing about technology and gadgets. He has completed B.Tech. Apart from writing, he likes to spend his time on his plantation.

Download PC Repair Tool to quickly find & fix Windows errors automatically

A Shell is a program that uses the command line interface or graphical user interface and allows users to access and control their computers by entering commands. The program is named Shell because it is the outermost layer of an operating system. The shell acts as a communication medium between a user and an operating system.

PowerShell is a command-line and scripting tool in Windows 10. It is developed by Microsoft Corporation and is used for the automation of tasks and configuration management. PowerShell ISE is another tool developed by Microsoft Corporation which is used for creating, running, and debugging commands and scripts. In PowerShell ISE, ISE stands for Integrated Scripting Environment. Hence, PowerShell ISE also comprises some advanced features that Windows PowerShell does not have.

PowerShell Vs PowerShell ISE

While PowerShell uses a command-line interface (CLI), PowerShell ISE uses a graphical user interface (GUI). Because GUI is easy to use and understand, users can execute and debug commands and scripts without writing all the commands in the command-line interface. Apart from this, there are several more features that make PowerShell ISE more advanced than PowerShell. This article illustrates the difference between Windows PowerShell and Windows PowerShell ISE.

What is PowerShell ISE?

As described above in this post, PowerShell ISE is a GUI-based application that lets users run and debug commands and scripts.

Let’s see the features of PowerShell ISE:

  • Multiline editing: By using this feature, you can insert an empty line under the current line in the Command Pane. To use the Multiline editing feature, you have to press the Shift  + Enter keys on your keyboard.
  • Selective execution: This feature lets you run a part of a script by selecting the text. After selecting the text, you simply have to click on the Run Script button. The F5 key is the shortcut to this feature.
  • Context-sensitive help: It opens a help file. To use this feature, type Invoke-Item and then press the F1 key.

Read: Windows Terminal Tips and Tricks.

We will compare these tools based on the following properties/features:

  1. User-interface
  2. Tasks
  3. Editing the commands and scripts
  4. Context-sensitive Help
  5. Command Add-ons

1] User-interface

We have described above in this article that PowerShell has a command-line interface, whereas the PowerShell ISE comes with a graphical user interface. Due to this, PowerShell offers a user-friendly interface and is easy to use and understand for beginners.

If you compare the interface of both of these tools, you will find that PowerShell ISE comes with an attractive interface with a toolbar, menu bar, script pane, console pane, multiple tabs feature, etc.

2] Tasks

Because you can open multiple tabs in PowerShell ISE, it is a multitasking tool. You can run multiple commands and scripts in PowerShell ISE in different tabs. This feature is not available in PowerShell.

TIP: Posterpedia is a cool Microsoft Store app that will help you understand Microsoft technologies.

3] Editing commands and scripts

Editing a script in PowerShell ISE is easy as it comes with a number of tools that you can use for editing. If you click on the Edit menu, you will see the following features:

  • Find in script
  • Find next in script
  • Find previous in script
  • Replace in script
  • Go to line
  • Go to match

These features save your time by making the script editing process hassle-free. On the other hand, the Edit menu is not available in PowerShell, which makes the script editing process a bit time-consuming in case the script is long.

Read: How to Install and Use Windows PowerShell ISE.

4] Context-sensitive help

The context-sensitive help feature is not available in PowerShell.

Read: Terminal vs PowerShell vs Command Prompt difference explained

5] Commands Add-ons

In PowerShell ISE, a command add-ons panel is available on the right side of the interface. You can search for a particular command and insert it into the Console Pane by clicking on the Insert button. You can also filter the commands by clicking on the drop-down menu.

Such a type of panel is not available in PowerShell.

That’s it.

Related reads:

  • PowerShell opens at Startup.
  • How to disable PowerShell.

Ezoic

Nishant is a tech enthusiast who loves writing about technology and gadgets. He has completed B.Tech. Apart from writing, he likes to spend his time on his plantation.

Оболочка — это программа, которая использует интерфейс командной строки или графический интерфейс пользователя и позволяет пользователям получать доступ к своим компьютерам и управлять ими путем ввода команд. Программа называется Shell, потому что это самый внешний уровень операционной системы. Оболочка действует как средство связи между пользователем и операционной системой.

PowerShell — это инструмент командной строки и сценариев в Windows 10. Он разработан корпорацией Microsoft и используется для автоматизации задач и управления конфигурацией. PowerShell ISE — еще один инструмент, разработанный корпорацией Microsoft, который используется для создания, выполнения и отладки команд и сценариев. В PowerShell ISE ISE означает интегрированную среду сценариев. Следовательно, PowerShell ISE также включает некоторые расширенные функции, которых нет в Windows PowerShell.

PowerShell против PowerShell ISE

В то время как PowerShell использует интерфейс командной строки (CLI), PowerShell ISE использует графический интерфейс пользователя (GUI). Поскольку графический интерфейс прост в использовании и понимании, пользователи могут выполнять и отлаживать команды и сценарии, не записывая все команды в интерфейсе командной строки. Помимо этого, есть еще несколько функций, которые делают PowerShell ISE более продвинутой, чем PowerShell. В этой статье показано различие между Windows PowerShell и Windows PowerShell ISE.

Что такое PowerShell ISE?

Как описано выше в этом посте, PowerShell ISE — это приложение на основе графического интерфейса пользователя, которое позволяет пользователям запускать и отлаживать команды и сценарии.

Давайте посмотрим на особенности PowerShell ISE:

  • Многострочное редактирование: с помощью этой функции вы можете вставить пустую строку под текущей строкой на панели команд. Чтобы использовать функцию многострочного редактирования, вы должны нажать клавиши Shift + Enter на клавиатуре.
  • Выборочное выполнение: эта функция позволяет запускать часть сценария, выделяя текст. После выбора текста вам просто нужно нажать кнопку «Выполнить сценарий». Клавиша F5 — это ярлык для этой функции.
  • Контекстно-зависимая справка: открывает файл справки. Чтобы использовать эту функцию, введите Invoke-Item и нажмите клавишу F1.

Прочтите: Советы и хитрости Windows Terminal.

Мы сравним эти инструменты на основе следующих свойств / функций:

  1. Пользовательский интерфейс
  2. Задания
  3. Редактирование команд и скриптов
  4. Контекстно-зависимая справка
  5. Командные надстройки

1]Пользовательский интерфейс

Выше в этой статье мы описали, что PowerShell имеет интерфейс командной строки, тогда как PowerShell ISE поставляется с графическим пользовательским интерфейсом. Благодаря этому PowerShell предлагает удобный интерфейс и прост в использовании и понимании для новичков.

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

2]Задачи

Поскольку в PowerShell ISE можно открывать несколько вкладок, это инструмент многозадачности. Вы можете запускать несколько команд и сценариев в PowerShell ISE на разных вкладках. Эта функция недоступна в PowerShell.

СОВЕТ: Posterpedia — отличное приложение из Microsoft Store, которое поможет вам разобраться в технологиях Microsoft.

3]Редактирование команд и скриптов

Редактировать скрипт в PowerShell ISE очень просто, поскольку он поставляется с рядом инструментов, которые вы можете использовать для редактирования. Если вы нажмете на меню «Правка», вы увидите следующие функции:

  • Найти в скрипте
  • Найти далее в скрипте
  • Найти предыдущее в скрипте
  • Заменить в скрипте
  • Перейти к строке
  • Перейти к матчу

Эти функции экономят ваше время, упрощая процесс редактирования сценария. С другой стороны, меню «Правка» недоступно в PowerShell, что делает процесс редактирования скрипта немного трудоемким, если скрипт длинный.

Прочтите: Как установить и использовать Windows PowerShell ISE.

4]Контекстно-зависимая справка

Функция контекстной справки недоступна в PowerShell.

5]Команды надстройки

В PowerShell ISE панель надстроек команд доступна в правой части интерфейса. Вы можете найти определенную команду и вставить ее в панель консоли, нажав кнопку «Вставить». Вы также можете отфильтровать команды, щелкнув раскрывающееся меню.

Такой тип панели недоступен в PowerShell.

Вот и все.

Связанные чтения:

PowerShell против PowerShell ISE .

PowerShell vs PowerShell ISE

Difference Between PowerShell vs PowerShell ISE

Generally, a shell is defined as a user interface that provides access to various features on the operating system. It can also be based on a command-line interface or graphical user interface. PowerShell is developed for configuration management and automation of tasks. It works on a shared platform and available as an open-source. PowerShell ISE is expanded as PowerShell Integrated scripting environment which is a graphical user interface that enables the user to execute commands, create and modify the scripts directly on the GUI instead of typing as a command.

Head to Head Comparisons Between PowerShell vs PowerShell ISE (Infographics)

Below are the top comparisons between PowerShell vs PowerShell ISE:

PowerShell vs PowerShell ISE info

Key Differences between PowerShell vs PowerShell ISE

The configuration and applications of PowerShell and PowerShell ISE can be varied a lot. But its significant features are discussed below. Let us discuss some of the major key differences:

1. User-Interface of PowerShell and PowerShell ISE

The PowerShell can be installed in macOS, Linux and especially on Windows. In initial stages, it is developed based on the .NET framework along with scripting language and command-line interface. Windows developed a command-line interface especially to fit its programming language. But as an up-gradation to CLI, Windows came up with a powerful tool which is PowerShell ISE which can perform all the smart works of the admin. It can execute advanced features such as running repeated sequences of commands to compute the configuration of the servers. It enables the development of scripts that is the collection of commands where the user can give input as a complex logic for the execution.

2. Special Features

A segregated command panel is also configured to execute the interactive PowerShell ISE scripts. The admin can alter the application settings to any color, layout, font and tailor text. It can also employ column and line numbers, shortcut for keyboard, the feature of context-sensitive help to adjust the editing environment. whereas in the PowerShell no such advanced features are available. It has only default configuration settings.

3. Multitasking

PowerShell can supports multithreading by executing simple commands such as start-jobs to schedule the background jobs and PowerShell run space commands. The PowerShell ISE supports eight parallel executions. It enables the copy and paste of multiple code lines to make the easier editing of the scripts. It includes an extensive debugger for command testing by using entire scripts or sections of scripts. It can also check variables and add breakpoints to view the behavior of scripts at specific points. Snippet stores the shorter segment of codes for reuse and frequently used lists provide rapid access to recent files.

4. Updated Versions

The initial version of PowerShell was updated in November 2006 for Windows 2003, Windows XP, and Windows Vista. Now the recent version is Windows PowerShell 5.1 in the year 2016 at the time of windows 10-anniversary update. It is also implemented for Windows sever 2008 R2, Windows Server 2012 R2, and Windows server 2012, Pro and editor versions of Windows 8.1 and also in Windows 7 Service Pack 1. The latest version of PowerShell ISE happened along with the Windows 2.0 version with Intellisense for auto-completion of cmdlets, files, values, parameters and other variables. The Auto-save option store the script for every minute to avoid data loss in case of any crashes.

5. Weapon of Choice

In PowerShell, for effectively managing the higher dimensional of servers in a network it is mandatory to implement a new security solution which is relied on specific jobs or applications that have to be executed on the servers. The user can check by logging into every server to check the status of the job, but it is a waste of time and takes time to complete the task. But the application of PowerShell ISE takes a few minutes to execute and complete the entire operation with the help of one script that holds all the data about the services on the servers. It is specified and dumped as a text file. Hence it is the time-consuming process. So it simplifies all sorts of tedious processes with the help of stored scripts.

Comparison Table of PowerShell vs PowerShell ISE

Let’s look at the top comparisons between PowerShell vs PowerShell ISE:

Basis of Comparison  PowerShell PowerShell ISE
Definition The PowerShell is a command-line interface that is operated with the help of input commands. IT is mainly applied to the automation of tasks. The PowerShell ISE is a graphical user interface that is used to performs automated simple act ivies in GUI pane such as create, modify, edit and run without any help of commands.
Console The application of the PowerShell console is general The application console or PowerShell ISE is attractive, colorful and user-friendly
Copy-Paste The data Here alt + space+ E + P is used Here in the clipX option, it can use ctrl + V which is very convenient to the user
Editing the File The execution of a longer command is difficult. Here the user has to search the line, fix the bug, copy or paste the data by typing as commands Here to edit the line pressing F8, throws the user several options for editing.
Context-Sensitive The context-sensitive help is not available in the command line interface panel. Here the dialog box appears, suggesting a related text suitable to execute the perfect command.
Size of the Window It is easier to maximize and minimize the window size. It takes much time to read and write in a single long line. It behaves like a common window application and can be resized easily
STA It should be configured in PowerShell. STA is a default option in PowerShell ISE.

Conclusion

PowerShell is one of the parts of the Windows management framework that enables the admin to manage multiple versions of Windows servers within the organization. It can install a set of features like PowerShell Desired state configuration, windows remote management, windows PowerShell web services, server manager CIM provider, software inventory login, windows management instrumentation.

Recommended Articles

This is a guide to PowerShell vs PowerShell ISE. Here we discuss the key differences with infographics and comparison tables. You can also go through our other related articles to learn more –

  1. PowerShell vs Python
  2. PowerShell vs CMD
  3. PowerShell vs Command Prompt
  4. PowerShell vs Bash

0 / 0 / 0

Регистрация: 28.04.2016

Сообщений: 10

1

07.08.2016, 14:38. Показов 6165. Ответов 3


Скажите, пожалуйста, чем PowerShell отличается от PowerShell ISE. Спасибо.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Покинул форум

4659 / 1303 / 335

Регистрация: 07.05.2015

Сообщений: 2,598

07.08.2016, 15:40

2

Цитата
Сообщение от Calvin Candie

Скажите, пожалуйста, чем PowerShell отличается от PowerShell ISE. Спасибо.

Хост PowerShell — интерпретатор команд и сценариев, написан на СС++, вспомогательные сборки на C#. ISE (Integrated Scripting Environment) — интегрированная среда сценариев, написана полностью на C#, представляет собой обертку над хостом PowerShell, а также набор инструментов для быстрого написания и тестов сценариев, из-за того что спроектирован на WPF может притормаживать и жрать безбожно ресурсы, именно по этой причине многие предпочитают менее тормознутую среду разработки сценариев — PowerShellGUI. Лично я предпочитаю Vim с установленной подсветкой синтаксиса для PowerShell и настроенный на исполнение и отладку по хоткеям, ибо трата ресурсов незначительна, ну а сама консоль как-то привычней.



0



0 / 0 / 0

Регистрация: 28.04.2016

Сообщений: 10

09.08.2016, 06:34

 [ТС]

3

Цитата
Сообщение от greg zakharov
Посмотреть сообщение

Хост PowerShell — интерпретатор команд и сценариев, написан на СС++, вспомогательные сборки на C#. ISE (Integrated Scripting Environment) — интегрированная среда сценариев, написана полностью на C#, представляет собой обертку над хостом PowerShell, а также набор инструментов для быстрого написания и тестов сценариев, из-за того что спроектирован на WPF может притормаживать и жрать безбожно ресурсы, именно по этой причине многие предпочитают менее тормознутую среду разработки сценариев — PowerShellGUI. Лично я предпочитаю Vim с установленной подсветкой синтаксиса для PowerShell и настроенный на исполнение и отладку по хоткеям, ибо трата ресурсов незначительна, ну а сама консоль как-то привычней.

Так. Я правильно понимаю, что это что-то типа оболочки в которой пишутся собственно сценарии, которые в свою очередь могут быть сохранены как скрипт файл? Это что-то типа AutoIT по смыслу?



0



773 / 422 / 137

Регистрация: 03.06.2009

Сообщений: 1,223

Записей в блоге: 4

09.08.2016, 11:18

4

Calvin Candie,
Сценарии, собственно можно писать и в текстовом документе(при должном знании синтаксиса), ISE в общем случае, создан лишь для удобства, в нем есть подсветка синтаксиса, описание командлетов, средства отладки и прочие приблуды.



0



I know of at least 10 reasons why the PowerShell ISE is a much better command prompt than the PowerShell console.

Contents

  1. Copy commands
  2. Paste commands
  3. Editing
  4. Switch to scripting
  5. Window size
  6. Context sensitive help
  7. Command Add-on
  8. Syntax highlighting
  9. Tabs
  10. Zoom
  • Author
  • Recent Posts

Michael Pietroforte is the founder and editor in chief of 4sysops. He has more than 35 years of experience in IT management and system administration.

One of the things that really puzzles me about PowerShell is its shell. Obviously, the “Power” in PowerShell is not in any way related to its official user interface. I believe this shell hasn’t changed since Windows 95, and it was already an awkward command-line interface (CLI) at that time. I think I could fill a book with all its shortcomings. If you also work in the Linux world, you know what I am talking about.

However, Windows comes with a command-line interface for PowerShell that fits much better with this powerful language. By the way, if you can’t find PowerShell ISE on your Start Screen, this post explains how you can make ISE tile visible. Many admins think that the Windows PowerShell Integrated Scripting Environment (ISE) is only for writing scripts. Perhaps the reason is that “ISE” sounds a little like “IDE” (Integrated Development Environment). Thus, whenever they need a PowerShell console, they launch this old-fashioned “Windows 95 DOS prompt.”

PowerShell ISE as CLI

PowerShell ISE as CLI

Of course, PowerShell ISE is a great scripting tool; however, it is also a powerful CLI. You can simply reduce the size of script editor or minimize altogether, and then you have a very nice PowerShell console. Below, I list 10 reasons why you should use PowerShell ISE as your primary CLI. In this article, I talk about the PowerShell prompt or console when I mean the official shell, and I speak of the PowerShell ISE prompt when I mean the integrated CLI in PowerShell ISE.

Copy commands

Did you ever try to copy a command that is longer than one line at the PowerShell prompt? I don’t know who had this idea that it could be useful to mark text as a block instead of selecting it line by line. I don’t remember ever needing such a strange way to select text. I am also not aware of a method of selecting text on the console without a mouse. In the PowerShell ISE, you can highlight text as in any editor—that is, line by line and by using the SHIFT + cursor keys. You can copy the text as you are used to with CTRL+C.

Select text in the PowerShell console

Select text in the PowerShell console

Paste commands

Pasting is also somewhat inconvenient on the console. The fastest way is to right-click (if Quick Edit Mode is enabled), but real PowerShell geeks avoid clicking whenever possible. ALT+SPACE+E+P is not really a convenient alternative. In PowerShell ISE, you can just paste as usual with CTRL+V. However, what is much more important for me is that my clipboard history tool ClipX works in PowerShell ISE. Scrolling through previous commands with the cursor keys is only half as efficient because you see all your previous commands at a glance with ClipX. Note that if you want to use ClipX with an elevated PowerShell ISE console, you also have to run ClipX with admin privileges.

Editing

I also find it very convenient to have an editor right at hand in PowerShell ISE. Sometimes, when I experiment with a long command, I keep different versions of it in an editor and copy and paste it to the PowerShell ISE prompt. (Yeah, I try to avoid type-type-type whenever I can.) I also sometimes launch a command directly from the PowerShell ISE by pressing F5. If I have several versions of the command in the editor, I just select a particular line and press F8. You can also run part of a command in the editor by highlighting the portion and then pressing F8.

Run selection in PowerShell ISE

Run selection in PowerShell ISE

Switch to scripting

I often notice that the things I want to do are not as simple as I assumed. Piping is fun, but sometimes you reach a point where you realize that you had better write a little script. Since I already have most of the commands in my editor from my experiments, I can easily switch from CLI mode to scripting. Honestly, I don’t think that there is a real difference between using a CLI and scripting. A command is just a script with a single line.

Window size

One of the most annoying shortcomings of the PowerShell prompt is that you can’t just enlarge the window with the mouse; if you click the full screen symbol, you only get a window with the number of lines you configured in the window properties. By contrast, the PowerShell ISE window behaves like a normal Windows application and can easily be resized. PowerShell commands tend to be quite long, and they are easier to read and edit if you can keep them on one line without a line break.

Context sensitive help

One very useful feature of the PowerShell ISE editor is the context sensitive help. When you start typing, a little window pops up that displays the cmdlets that match the entered text. So, if you are not sure about the exact name of the cmdlet, you can start typing and then scroll through the different options. Also very useful is that, if you type “-” after entering the cmdlet’s name, PowerShell ISE will show you the available parameters. After you complete the parameter, you even get a list of its possible options. This only works in the editor, not in PowerShell ISE’s CLI. But this is not an issue since you can just launch the command from the editor with F5 instead of pressing Enter.

PowerShell ISE - Context sensitive help

PowerShell ISE — Context sensitive help

Command Add-on

If you click the Command Add-on in PowerShell ISE’s toolbar, a sidebar will show up on the right where you can search for cmdlets. You can also restrict your search to a particular module.

PowerShe ISE - Show Command Add-on

PowerShe ISE — Show Command Add-on

Syntax highlighting

Of course, PowerShell ISE also supports syntax highlighting. This helps avoid syntax errors and makes your command easier to read when you verify it before you fire it up.

PowerShell ISE - Syntax highlighting

PowerShell ISE — Syntax highlighting

Tabs

The PowerShell ISE tabs come in handy if you work on multiple administration tasks simultaneously. I find it much more convenient than working with multiple PowerShell console windows. For each tab, you have your own editor.

PowerShell ISE tabs

PowerShell ISE tabs

Zoom

If you work a lot with PowerShell, you will notice that it strains your eyes a lot. Coders are an eye doctor’s best customers. If you worked all day on the CLI and you simply can’t see the syntax error, you can do your eyes a favor and enlarge the fonts. As with any other Windows application, you can zoom with the mouse wheel while pressing the CTRL key. Another way to zoom is CTRL + to increase the font size and CTRL — to decrease it. This works in the editor and in the CLI of PowerShell ISE.

Did I convince you? If not, why do you still prefer the PowerShell console over the PowerShell ISE CLI?

Also read:

  • NEW: PowerShell ISE Module Browser
  • PowerShell Script Browser and Script Analyzer – Must-have tools for scripters

Рассказываем про Windows PowerShell — технологию для автоматизации рутинных задач, пришедшую на смену bat-файлам.

Работа с консолью Microsoft Windows

Ранее мы рассматривали командные интерпретаторы COMMAND.CMD и CMD.EXE, обеспечивающие автоматизацию задач в семействе операционных систем Microsoft Windows. Фактически данные интерпретаторы не получали обновлений с начала 2000-х годов и существуют в современных операционных системах для обеспечения совместимости.

Подробнее о bat-файлах →

Хотя современные операционные системы предлагают богатый на функции графический интерфейс, ряд однотипных задач быстрее решается через консоль. Более того, серверные редакции ОС не предоставляют графический интерфейс по умолчанию, поэтому интерпретатор командной строки является неотъемлемой частью практически любой операционной системы.

Помимо отсутствия обновлений, CMD.EXE имеет ограниченный функционал. Он не позволяет писать сложную логику и полностью отказаться от использования графического интерфейса. Корпорация Microsoft пыталась решить эти проблемы с помощью инструмента под названием Microsoft Script Host, который имел интеграцию со скриптовыми языками JScript и VBScript.

Однако Microsoft Script Host имел ряд собственных проблем:

  • плохо интегрировался с командной оболочкой операционной системы,
  • сопровождался скудной документацией,
  • разные версии Windows имели командные интерпретаторы с разным набором команд,
  • инструмент становился отличным вектором для атак.

Все это побуждало Microsoft сделать командный интерпретатор с нуля.

В 2003 году корпорация Microsoft начала разработку нового инструмента — Microsoft Shell (MSH), или Monad. Спустя три года и три бета-версии Monad была официально выпущена под новым названием Windows PowerShell 1.0 на Windows XP и Windows Vista. По ходу развития командная оболочка меняла свои названия на PowerShell Core и PowerShell.

При создании PowerShell разработчики задались целью создать инструмент, который позволил бы с легкостью использовать множество разнородных интерфейсов, предоставляемых операционной системой. Новый инструмент должен быть консистентным и легким для администратора, несмотря на количество технологий «под капотом». Например, PowerShell предоставляет доступ к API .NET-фреймворка, но не требует от администратора знания .NET.

Как и любой командный интерпретатор, PowerShell умеет запускать исполняемые файлы и имеет встроенные команды. Однако у PowerShell встроенные команды имеют название «командлет», появившееся от английского cmdlet.

Что такое командлет?

В основе взаимодействия с PowerShell лежат объекты, а не текст, как у CMD.EXE и командных интерпретаторов в *nix-системах. Такой подход меняет взгляд на организацию встроенных команд.

Командлет — это встроенная команда в PowerShell, выполняющая одну задачу и реализованная на .NET. Имя командлета соответствует правилу Глагол-Существительное, которое можно читать как Действие-Объект.

Самый важный командлет, о котором необходимо узнать в первую очередь, — Get-Help. Он отображает справочную информацию о PowerShell и командлетах.

# Получить общую справку по PowerShell
Get-Help

# Получить справку по командлету Get-Content
Get-Help Get-Content

# Получить справку по командлету Get-Help
Get-Help Get-Help

Если вам кажется, что использовать большие буквы в названии командлетов — это перебор, для вас есть хорошие новости. Все команды в PowerShell являются регистронезависимыми. Иными словами, перечисленные ниже написания эквивалентны:

Get-Help Get-Help
get-help get-help
GET-HELP GET-HELP
GeT-hElP gEt-HeLp

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

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

Основы программы PowerShell

Перейдем к практике. PowerShell является кроссплатформенным инструментом и может быть запущена на Linux и macOS, но в данной статье будет рассматриваться только «родное» окружение — Windows.

Как запустить?

Программа в меню

Запуск PowerShell можно произвести из меню поиска около кнопки Пуск, набрав powershell.

PowerShell в меню

Аналогично можно запустить PowerShell через диалоговое окно Выполнить…, которое открывается через сочетание клавиш Windows + R.

Если по каким-то причинам у вас не установлен PowerShell, то необходимо сделать это, следуя инструкции в базе знаний Microsoft.

Установка PowerShell

В случае успеха откроется синее окно. Windows PowerShell готов к вашим командам.

Синтаксис

Синтаксис PowerShell похож на синтаксис других командных интерпретаторов. Сначала команда, а затем аргументы команды. Несколько команд в одной строке разделяются точкой с запятой. Рассмотрим на примере.

Get-Help Get-Command -Online

Данная команда откроет в браузере вкладку с описанием командлета Get-Command в базе знаний Microsoft. Разберем подробнее:

  • Get-Help – команда, в данном случае командлет,
  • Get-Command – первый позиционный аргумент, который передается командлету,
  • -Online – ключ, то есть именованный аргумент.

Обратите внимание, что в CMD.EXE именованные аргументы, то есть ключи, для встроенных команд начинались с символа слэш (/). У командлетов аргументы начинаются со знака минус. Использование знака / в PowerShell недопустимо и будет интерпретировано как ошибка.

Хотя PowerShell во многом похож на CMD.EXE, он имеет несколько существенных отличий. Во-первых, обращение к переменным производится через символ доллар, а не через знак процента. Во-вторых, PowerShell позволяет определять функции. Например:

function Get-Version {
    $PSVersionTable.PSVersion
}

Данный код объявит функцию Get-Version, которая обращается к системной переменной (объекту) PSVersionTable и возвращает значение поля PSVersion. Проще говоря, выводит версию PowerShell.

Именование командлетов может быть неочевидным для администраторов с опытом работы с другими командными интерпретаторами. Поэтому рассмотрим основные команды Windows PowerShell.

Основные команды языка Windows PowerShell

В следующей таблице перечислены основные команды PowerShell и их аналоги в *nix-подобных системах и CMD.EXE. В версии PowerShell 7 количество командлетов превышает полторы тысячи!

Командлет (псевдоним) Команда в *nix Команда в CMD.exe Описание
Get-Location (pwd) pwd Выводит путь до текущего каталога
Set-Location (cd) cd cd Меняет текущий каталог
Get-ChildItem (ls) ls dir Выводит содержимое текущего каталога
Get-ChildItem find find Производит поиск файлов по заданным критериям
Copy-Item (cp) cp cp Копирует файл
Remove-Item (rm) rm rm Удаляет файл
New-Item (mkdir) mkdir mkdir Создает каталог
New-Item touch Создает пустой файл
Get-Content (cat) cat Выводит файлы
Get-Content tail Выводит последние 10 строк
Where-Object grep Производит фильтрацию
Create-Volume
Format-Volume
mkfs Форматирует раздел
Test-Connection ping ping.exe Отправляет ICMP-запросы, «пингует»
Get-Help (man) man help Показывает справку

После работы в консоли *nix командлет для популярного действия, смены каталога, выглядит громоздко и непривычно. К счастью, командлеты имеют псевдонимы (алиасы), которые могут не следовать правилу именования командлетов. Список известных псевдонимов можно получить с помощью командлета Get-Alias.

Хотя таблица, представленная выше, значительно облегчит назначение командлетов, не стоит ожидать от командлетов поведения как в *nix-системах. Так, например, в PowerShell командлет Get-Content создан для вывода содержимого одного файла на экран, в то время как на *nix-системах утилита cat изначально использовалась для конкатенации (процесса соединения) нескольких файлов с последующим выводом на экран.

Очевидно, что возможности PowerShell значительно больше, чем CMD.exe. Опытный администратор знает, что некоторые задачи из таблицы можно решить в CMD.exe, несмотря на отсутствие специальных команд. Однако эти команды требуют опыта или смекалки.

Утилита ping

Отдельно хочется отметить командлет Test-Connection, который делает то же самое, что утилита ping, но не имеет такого алиса. Разница между утилитой и командлетом в формате вывода: утилита выводит текст, а командлет возвращает объект, который можно использовать в конвейерах.

Конвейер PowerShell: особенности и параметры

По своей задумке конвейеры в PowerShell не отличаются от конвейеров в *nix-системах: они перенаправляют вывод одной команды на ввод другой. Как отмечалось ранее, в PowerShell происходит взаимодействие не с текстом, а с объектами. При выводе на экран объект трансформируется в таблицу, чтобы человеку было удобнее читать, но не всегда таблица выводит все поля объекта.

Особенность конвейеров PowerShell заключается в том, что конвейер передает результат не целиком, а по одному объекту. Командлет Test-Connection выводит четыре объекта: по одному на каждый ICMP-запрос. Если подключить командлет к конвейеру, то можно увидеть подтверждение этому тезису. Воспользуемся командлетом Select-Object, чтобы выбрать колонку со временем запроса.

Test-Connection selectel.ru | Select-Object ‘Time(ms)’

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

Test-connection

Но как же так? Дело в том, что отображение объекта при выводе на экран не всегда соответствует имени поля в объекте. Чтобы получить полный список полей в объекте, необходимо вызвать командлет Get-Member.

PS C:Userssun> Test-connection selectel.ru | Get-Member


   TypeName: System.Management.ManagementObject#rootcimv2Win32_PingStatus

Name                           MemberType     Definition
----                           ----------     ----------
PSComputerName                 AliasProperty  PSComputerName = __SERVER
Address                        Property       string Address {get;set;}
BufferSize                     Property       uint32 BufferSize {get;set;}
NoFragmentation                Property       bool NoFragmentation {get;set;}
PrimaryAddressResolutionStatus Property       uint32 PrimaryAddressResolutionStatus {get;set;}
ProtocolAddress                Property       string ProtocolAddress {get;set;}
ProtocolAddressResolved        Property       string ProtocolAddressResolved {get;set;}
RecordRoute                    Property       uint32 RecordRoute {get;set;}
ReplyInconsistency             Property       bool ReplyInconsistency {get;set;}
ReplySize                      Property       uint32 ReplySize {get;set;}
ResolveAddressNames            Property       bool ResolveAddressNames {get;set;}
ResponseTime                   Property       uint32 ResponseTime {get;set;}
ResponseTimeToLive             Property       uint32 ResponseTimeToLive {get;set;}
RouteRecord                    Property       string[] RouteRecord {get;set;}
RouteRecordResolved            Property       string[] RouteRecordResolved {get;set;}
SourceRoute                    Property       string SourceRoute {get;set;}
SourceRouteType                Property       uint32 SourceRouteType {get;set;}
StatusCode                     Property       uint32 StatusCode {get;set;}
Timeout                        Property       uint32 Timeout {get;set;}
TimeStampRecord                Property       uint32[] TimeStampRecord {get;set;}
TimeStampRecordAddress         Property       string[] TimeStampRecordAddress {get;set;}
TimeStampRecordAddressResolved Property       string[] TimeStampRecordAddressResolved {get;set;}
TimestampRoute                 Property       uint32 TimestampRoute {get;set;}
TimeToLive                     Property       uint32 TimeToLive {get;set;}
TypeofService                  Property       uint32 TypeofService {get;set;}
__CLASS                        Property       string __CLASS {get;set;}
__DERIVATION                   Property       string[] __DERIVATION {get;set;}
__DYNASTY                      Property       string __DYNASTY {get;set;}
__GENUS                        Property       int __GENUS {get;set;}
__NAMESPACE                    Property       string __NAMESPACE {get;set;}
__PATH                         Property       string __PATH {get;set;}
__PROPERTY_COUNT               Property       int __PROPERTY_COUNT {get;set;}
__RELPATH                      Property       string __RELPATH {get;set;}
__SERVER                       Property       string __SERVER {get;set;}
__SUPERCLASS                   Property       string __SUPERCLASS {get;set;}
ConvertFromDateTime            ScriptMethod   System.Object ConvertFromDateTime();
ConvertToDateTime              ScriptMethod   System.Object ConvertToDateTime();
IPV4Address                    ScriptProperty System.Object IPV4Address {get=$iphost = [System.Net.Dns]:...
IPV6Address                    ScriptProperty System.Object IPV6Address {get=$iphost = [System.Net.Dns]:...

Можно визуально оценить список и найти поле ResponseTime. Также в начале указан тип данного объекта, Win32_PingStatus, информацию о котором можно поискать в базе знаний Microsoft. В документации не только перечислены поля, но и их назначение. Таким образом, конечный вид конвейера будет таким:

Test-connection selectel.ru | Select-Object ResponseTime

Хотя PowerShell побуждает к интерактивной работе, его основное предназначение — автоматизировать рутинные задачи. Значит, необходимо писать скрипты.

Используйте PowerShell в работе с выделенным сервером

Соберите сервер в конфигураторе под свои задачи. Или выберите из более 100 готовых.

Подобрать

Интегрированная среда разработки

Среда разработки

Если вы запускали PowerShell через поиск, вероятно, вы могли заметить приложение Windows PowerShell ISE.

PowerShell-скрипты — это текстовые файлы с расширением .ps1.

Windows PowerShell ISE — это интегрированная среда сценариев PowerShell, включающая в себя:

  • редактор PowerShell-скриптов с автодополнением,
  • окно для интерактивного выполнения командлетов в скрипте,
  • список доступных командлетов с поиском.
Перечень команд
Справка Test-Connection

Обратите внимание, что модуль ISE предоставляет графический интерфейс для генерации аргументов командлета. Помимо генерации команд, в функции модуля также входит вызов «справочника» по командлетам, аналогичного Get-Help, только в графическом интерфейсе.

После написания своего первого PowerShell-скрипта вы столкнетесь с некоторыми ограничениями. Во-первых, файл с расширением ps1 нельзя запустить «двойным кликом» по файлу. Необходимо открыть контекстное меню с помощью правой клавиши мыши и выбрать Запустить с помощью PowerShell.

Во-вторых, скрипт не запустится со следующей ошибкой:

Невозможно загрузить файл C:UserssunDocumentsHelloWorld.ps1, так как выполнение сценариев отключено в этой системе. Для получения дополнительных сведений см. about_Execution_Policies по адресу https:/go.microsoft.com/fwlink/
?LinkID=135170.
    + CategoryInfo          : Ошибка безопасности: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnauthorizedAccess

По умолчанию запуск PowerShell-скриптов ограничен соответствующей политикой безопасности. Посмотреть текущее значение политики безопасности можно с помощью командлет Get-ExecutionPolicy:

PS C:Userssun> Get-ExecutionPolicy
Restricted

Список возможных значений:

  • Restricted — запуск запрещен,
  • AllSigned — разрешен только запуск подписанных доверенным разработчиком скриптов,
  • RemoteSigned — разрешен запуск подписанных и собственных скриптов,
  • Unrestricted — разрешен запуск любых скриптов.

По умолчанию стоит значение Restricted. В идеале необходимо подписывать скрипты, но для собственных нужд можно ограничиться значением RemoteSigned:

Set-ExecutionPolicy RemoteSigned

Для выполнения данной команды необходимо запустить PowerShell от имени администратора.

Выполнение задач в фоне

Консоль PowerShell

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

  • Start-Job —  запустить команду или командлет в фоновом режиме,
  • Get-Job — показать состояние фоновых команд,
  • Wait-Job — дождаться завершения выполнения фоновой команды,
  • Receive-Job — получить результат выполнения команды.

Командлет Start-Job возвращает информацию о запущенном фоновом задании. Идентификатор, обозначенный в поле Id, является уникальным для сессии PowerShell.

Настройка удаленного выполнения

PowerShell позволяет реализовать удаленное выполнение командлетов, скриптов, но только на платформе Windows. Для включения возможности удаленного управления необходимо выполнить командлет Enable-PSRemoting с правами администратора.

Командлет Enter-PSSession запустит удаленную интерактивную сессию, а Invoke-Command выполнит команду на одном или нескольких удаленных компьютерах.

PowerShell – актуальные версии программы

PowerShell — мощный инструмент, пришедший на смену пакетным файлам. Он более функциональный и современный, а документация и различные руководства Windows PowerShell по работе делают его подходящим как для начинающих, так и продолжающих пользователей. В тексте мы составили описание PowerShell,  — рассмотрели основные возможности программы, понятия, связанные с ней, синтаксис PowerShell и структуру языка.

На момент написания статьи актуальная версия PowerShell — 7.2. Используйте этот текст в качестве краткого справочника по Windows PowerShell, администрирование систем со скриптами в этой программе будет довольно простым. 

Понравилась статья? Поделить с друзьями:
  • Вам понадобится новое приложение чтобы открыть этот ms gamingoverlay windows 11
  • Вай фай веб на компьютере windows
  • В чем отличие windows 7 professional от ultimate
  • Вам понадобится новое приложение чтобы открыть этот exe файл windows 10
  • В чем отличие windows 32 от windows 64 bit