PowerShell is a powerful tool for managing the Windows operating system and automating various tasks. It is an interactive command shell and scripting language, created specifically for the administration of the Windows platform. In our PowerShell tutorial, we’ll introduce you to the basics of using this tool and reveal its capabilities. You will learn how to work with the PowerShell command line, perform various operations with files and directories, manage services and processes, and configure system settings. One of the main advantages of PowerShell is its ability to automate tasks. You’ll learn how to create and run scripts that save time and effort on routine administration tasks.
The guide will be useful both for beginners who are just getting acquainted with PowerShell, and for experienced administrators who want to deepen their knowledge and optimize the workflow. Get ready to learn about the power of PowerShell and its potential for automating work on the Windows operating system. In addition to the basic features of PowerShell, our guide will also reveal an interactive mode where you can experiment with commands and test the results directly from the command line. Step-by-step examples and hands-on exercises will help you quickly master PowerShell and apply it in real-world scenarios. We’ll also show you how to work with variables, introduce loops, and conditional constructs, which will expand your scripting capabilities. In addition, you will learn how to integrate PowerShell with other tools and services such as Azure, Office 365, Active Directory, and more. This will open new horizons for the automation of management in various environments. With our guide, you’ll be able to optimize your workflow, improve productivity, and manage your Windows system more efficiently. Regardless of your experience with PowerShell, this guide will be a valuable resource for developing your skills and becoming more efficient with this powerful tool.
To communicate with a computer, laptop or mobile device, an intermediary – an operating system – is required. Any operating system can be represented as a set of the system kernel, which controls the hardware part and operates files and processes, and an interface that provides the user with access to the functionality of the kernel.
The interface can be of different types
Command-text, when commands for controlling the system are entered from the keyboard or taken from pre-prepared text files of scripts (scripts). In early operating systems, the command interface was unified.
Graphical, when you work in the system through various visual controls (buttons, drop-down lists, dialog boxes, etc.). The graphical interface is the main means of user interaction on modern personal computers and mobile devices.
A voice when a person simply utters commands to control the system. Recently, several systems of this type (Apple Siri, Microsoft Cortana, Google Now) that work on various mobile platforms have become widespread. The popularity of these voice assistants is growing, voice recognition technologies are developing, but it is not yet possible to say that voice control will completely replace graphic and text interfaces in the near future.
Of course, of course, today it is easier, more convenient and more familiar for an ordinary user to understand the graphical interface, there is no need to learn and remember special commands. Why even in the most modern operating systems for personal computers and servers, the command-text interface continues to be supported in the form of command-line shells and various program execution environments in special script languages (script languages)?
Of course, it is easier and more convenient for the user to understand the graphical interface today, there is no need to learn and remember special commands. Such automation may be necessary if we regularly perform the same type of operations (for example, copy documents changed during the day or, conversely, we need to perform one operation, but on many computers in the network (for example, change the path to a file in a shortcut on the desktops of hundreds of computers).
If such actions were performed using text commands, then they can be easily repeated without human intervention by creating a batch file (script) with these commands. This significantly increases the productivity of work with routine tasks.
Thus, the main advantage of the command-text interface is the possibility of automating the work of users and administrators with the help of script programs launched in the operating system.
In addition, scripts clearly define the order in which a task is performed, so you can use them as documentation. By saving your actions in the script, you won’t forget exactly what you did and why.
Finally, scripts allow you to automatically use services provided by internal objects of the operating system and other software (for example, office applications).
Learning scripting languages for the operating system can be useful for different people:
About the server, database or local networks, administrators simply need to have the skills to create and use scripts, without this their work will be very ineffective;
For an ordinary user, scripts are a useful additional tool for automating everyday activities: manipulating files, working with office applications and Internet resources;
Command-line scripting languages are one type of a wide range of scripting languages. The main task of such languages is to “assume” ready-made components available in the operating system (executable files, dynamic libraries, internal system objects, etc.), linking them together. In this way, script languages differ from traditional “system” programming languages (C, C++, Java, etc.), which were developed with the aim of building data structures and algorithms.
What would you like to see the ideal command shell and scripting language for automating work in the operating system?
Let’s list some of the requirements for such tools
Compatibility with all versions of the operating system currently in use and access to the widest possible range of operating system functions.
Simplicity and comprehensibility of the language – it should be accessible to ordinary users, not only professional programmers.
The ability to run external executables from a script in command mode without using additional constructs.
Support for both batch mode (writing and running scripts) and a convenient interactive command line (with short aliases for commands, autocompletion of commands and paths to files and directories, the ability to repeat previously entered commands, etc.).
Built-in help system and centralized script repository for common tasks.
Let’s now understand what we have in reality, what languages and shells can be used to automate work in modern operating systems.
Paraphrasing Karl Marx’s famous statement about being that determines consciousness, we can say that the operating system determines its shell. Command languages and shells were not created out of nowhere, they developed together with operating systems. New features have appeared in the system – a tool is needed to access these functions in automatic mode. As a result, you create a command-script programming language and an environment for executing commands and scripts in this language, which are naturally suitable for a specific operating system.
Almost all modern computers, laptops and servers run either Windows or one of the operating systems (macOS or Linux). Externally, the operating systems of these two families can be more or less similar to each other (for example, the Linux Mint graphical interface resembles Windows 7). However, the internal structure of Windows and UNIX has a fundamental architectural difference, which determined different ways of developing command shells and scripting languages for these operating systems and ultimately led to the creation of a truly unique and powerful automation tool – Microsoft PowerShell.
In operating systems (macOS or Linux), a terminal is used as a standard means of automation, in which commands and scripts of one or another modification of the original UNIX command shell (most often bash or zsh) are launched.
It was in UNIX in the distant 1970s that programming principles based on software tools were born and developed.
To solve a certain task, small utilities are developed, each of which performs one function of the problem to be solved.
The task is solved by the interaction of utilities (commands) due to sequential data processing of each of them.
When developing these utilities, they focus on their maximum independent use, which allows them to be used to solve other tasks. Thus, tools are gradually being created for further universal use.
Most utilities are filters that read input from the standard STDIN stream (the keyboard by default), process it, and output the result as a stream of text via the standard STDOUT stream to another device (the screen by default).
Command utilities connect to each other in operating system scripts by redirecting input/output and creating program pipelines (directing the output stream of one program to the input of another)
Various system settings, settings and program configurations are stored in plain text files. In general, in the UNIX world, textual data is usually used as a universal representation of information (except, of course, executable files in machine code, encrypted files and archives, graphic or multimedia files). Therefore, there are many powerful standard text processing utilities (grep, sed, awk, sort, cut, taj1, etc.).
Another basic principle of UNIX is expressed by the phrase “everything is a file”. In the form of (virtual) files, communication channels between programs, peripheral devices and virtual devices emulating the core of the operating system are presented. For example, to find out the processor parameters on a Linux computer, it is enough to print the contents of the cpuinfo virtual file in the /proc directory using the cat command:
cat /proc/cpuinfo processor vendor id 0 Genuinelntel cpu family model 6 58 20 Часть I. Знакомимся с PowerShell cache_alignment : 64 model name stepping microcode cpu MHz cache size physical id siblings core id : Intel(R) Core(TM) i7-3770S CPU @ 3.10GHz : 9 : Oxffffffff : 3092.986 : 8192 KB : 0 : 8 : 0 cpu cores apicid initial apicid fpu fpu exception cpuid level wp flags : 4 : 0 : 0 : yes : yes : 13 : yes : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 ciflush mmx fxsr sse sse2 ss ht syscall nx rdtscp lm constant tsc rep good nopl xtopology cpuid pni pclmulqdq ssse3 cxl6 pcid sse4 1 sse4 2 popcnt xsave avx fl6c rdrand hypervisor lahf lm pti ssbd ibrs ibpb stibp fsgsbase smep erms xsaveopt flush lid arch capabilities bugs : cpu meltdown spectre vl spectre v2 spec store bypass lltf mds swapgs itlb multihit srbds bogomips ciflush size : 6185.97 : 64 power management: address sizes : 36 bits physical, 48 bits virtual
Thus, simple automation tasks in systems ultimately boil down to working with the file system and word processing. It is convenient to solve such tasks by sequentially applying several commands combined by text streams into a pipeline (Fig. 1).
In more complex cases, when a pair of pipelines is not enough, scripting programs are written in a shell-supported scripting language (these languages are from the 1970s, they cannot be called convenient or intuitive) or in one of the general-purpose interpreted languages, the most popular of which is currently Python.
Microsoft Windows, which has been the most common operating system for personal computers and laptops for several decades, has several standard automation tools that vary widely. Let’s try to understand this variety, understand the reasons for the appearance of these tools and ultimately decide which automation tools are right for us.
Let’s start with the fact that Windows, unlike UNIX, has an API-oriented architecture: the operating system consists of a huge number of subsystems and components, which are accessed through a certain API (Application Program Interface), that is, special applications are needed to manage them. To simplify work with such a complex system, managed elements are grouped into structured objects.
This is the fundamental difference between Windows and systems that focus on using text to represent everything possible. Although you can administer by simply working with text configuration files, Windows must use a variety of APIs, accessing the properties and methods of many of Windows’ internal object models (.NET Framework, WMl, WSH, ADSl, CDO, etc.).
Thus, for effective automation of work in Windows, it is not enough to simply master the tools for working with the file system and processing text files, as in systems. In addition, it is necessary to be able to quickly, easily and evenly access various internal objects of the system from the command line or scripts.
At the time of writing this book, the latest version of Windows 10 has three standard (that is, does not require additional installation) tools for automating work in the operating system:
A command line interpreter cmd.exe that supports a simple (albeit quite specific) batch file language.
A Windows Script Host (WSH) scripting server that allows you to run VBScript and JScript scripts.
The Windows PowerShell shell and scripting environment.
In Windows 10 with the help of the WSL subsystem (Windows Subsystem for Linux), you can install a distribution from the Microsoft Store (for example, Debian and Ubuntu) and use its command shell to work with the Windows file system or launch Similarly, in this case, you will be able to run Linux utilities on the Windows command line. This hybrid approach provides interesting new opportunities for automation, but it is beyond the scope of this book and we will not cover it here.
These tools did not appear at the same time (batch files have been supported in Microsoft operating systems since the 1980s, and PowerShell appeared a quarter of a century later), they have different capabilities and to one degree or another satisfy the requirements for the ideal automation tool in Windows, which we discussed earlier.
There are two types of commands that can be executed in the standard Windows command line, which uses the cmd.exe interpreter:
Internal, performed directly by the interpreter itself
External, represented by executable utilities
As internal commands, operations with the file system and basic algorithmic operators (if, for) are implemented, which allow you to use batch files with the extension bat or cmd as simple script programs.
The cmd.exe interpreter supports the concept of standard text streams borrowed from UNIX and the mechanism of redistribution of input-output devices (Fig. 2).
Thus, in Windows, as in UNIX, text information (a stream of text) can be piped between several commands. I.G.).
The cmd.exe command line shell and batch files supported by this interpreter are the simplest and most versatile tools for automating simple tasks that will work reliably in any operating system configuration.
To create batch files, you need to know very little: the syntactic features of the cmd.exe interpreter and the capabilities of several dozen internal commands and standard command line utilities. The specific keys to launch these commands and utilities can be found in the built-in help.
Code listing 1.1. Example of a batch file (interpreter cmd.exe)
@echo off rem ***************************************************************** rem * Имя: sort_reps.bat rem * Язык: cmd.exe rem * Описание: Формирование списка каталогов с отчетами rem ***************************************************************** if exist temp.txt del temp.txt if exist odb.txt del odb.txt for /D %%f in (d:\odb2101*) do ( dir /s/Ь %%f\od*.htm » temp.txt) for /f "delims=\ tokens=4" %%i in ('sort /+17 temp.txt') do ( echo %%i » odb.txt) del temp.txt
However, cmd.exe batch files cannot be considered full-fledged scripts that allow you to use all the capabilities of Windows. The main problem is that Windows does not have standard convenient utilities for working with internal object models. In addition, the language of batch files itself is not sufficiently developed: it does not support work with arrays or structures, there are no logical operations in conditions, it is impossible to declare a function directly.
There is only one explanation for these shortcomings – historical. The fact is that the command interpreter cmd.exe appeared in the early 1990s, it is one of the earliest applications for the Windows NT operating system, on the basis of which all subsequent versions of Windows are built. The main task then was to achieve compatibility with the command.com shell of the previous MS-DOS operating system, which did not have any internal object systems. At that time, Microsoft focused on the widest possible audience of inexperienced users who did not want to delve into the technical details of the system. The main efforts of the developers were aimed at improving the graphical shell of the system for a more comfortable work of non-professionals, and not at creating a working environment for specialists (system administrators and developers) or experienced users.
To solve the problems listed above with the functionality and ease of use of traditional Windows batch files, two options were possible:
Expand the number of standard command line utilities and significantly expand the language of the cmd.exe interpreter, turning it into a full-fledged algorithmic language with support for object-oriented programming (at the same time, the modified command interpreter must also support the previous command file language syntax).
Choose another simple programming language for Windows scripts, which would be familiar to users of this operating system, would support all standard algorithmic capabilities and constructions, and also allow working with internal objects of the operating system.
Microsoft developers took the second path and in the early 2000s proposed using VBScript (Visual Basic Script Edititon) as the standard Windows scripting language. This language was chosen based on the following criteria.
About development. VBScript is a full-fledged algorithmic language that has built-in functions and methods for parsing character strings, performing mathematical operations, handling exceptions, etc.
Easy to learn. VBScript is based on BASlC (short for Begginner’s All-purpose Symbolic Instruction Code), which was developed in l964 at Dartmouth College as a special tool for writing programs by non-professionals. One of the main requirements that was taken into account when creating this language – ease of use for beginners.
Prevalence. BASlC was the standard programming language for home personal computers in the 1970s and 1990s. The first interpreter of this language from Microsoft (Altair BASIC) was developed back in 1975, until the end of the 1980s, BASIC was installed on almost all personal computers (both PC-compatible virtual machines and Apple computers). In Windows 95/98 operating systems, the Microsoft QBasic interpreter and development environment were installed as a standard system component.
Modifications of the BASIC language at that time were used in various areas of the Windows operating system.
Standard stand-alone Windows applications (Visual Basic is part of the Microsoft Visual Studio development environment).
Macros for automating work in Microsoft office applications (Visual Basic for Applications (VBA)).
Scripts in dynamic client scripts (VBScript was supported by Internet Explorer).
Scripts in the server for the web server lntemet lnformation Server.
Extensibility with external objects. VBScript has a CreateObj ect function that allows scripts to access and use many external objects registered with the operating system.
About the ability to add a graphical interface VBScript scripts can be embedded in the creation of so-called HTML applications.
To run VBScript and JScript scripts directly in the operating system, without a browser, a special Windows Script Host (WSH) script server was created, which is included by default in all versions of Windows since 2000.
WSH scripts are text files with the extension .vbs (VBScript language) or .js (JScript language). They can be run in text (console) mode using the cscript.exe program or in graphical mode using the wscript.exe file.
Listing 1.2. Example of a VBScript script
* Имя: MakeShortcut.vbs '* Язык: VBScript ’* Описание: Создание ярлыков из сценария Dim WshShell,oUrlLink 26 Часть I. Знакомимся с PowerShell ’ Создаем объект WshShell Set WshShell=WScript.CreateObject("WScript.Shell") ’ Создаем ярлык на сетевой ресурс Set oUrlLink = WshShell.CreateShortcut("Microsoft Web Site.URL") ’ Устанавливаем URL oUrlLink.TargetPath = "http://www.microsoft.com" ' Сохраняем ярлык oUrlLink.Save
WSH solves the problem that VBScript and JScript do not have special functions for managing the operating system (for example, these languages do not have functions for working with the file system). All the actual work in the script is performed by external objects, and WSH serves as an intermediary between them and the language interpreter (Figure 1.4).
Note that in addition to the standard Microsoft VBScript and JScript languages, other languages (for example, Perl or Python) can be used to write WSH scripts, for which you need to additionally install the corresponding support module.
Thus, WSH scenarios consist of two components (Fig. 1.5):
About the elements of the selected script language;
O external objects that do not depend on this language.
The ability to use full-fledged scripting languages and various external objects available in the operating system has made Windows Script Host a powerful automation tool. However, after a few years, it became clear that writing non-trivial practical scenarios is not an easy task for intermediate users and novice system administrators. If to create batch files it was enough to know the simple syntax of the language supported by cmd.exe and the capabilities of a couple of dozens of commands, then for a competent WSH script it was necessary to both study the chosen script of the script (although in the case of VBScript it is not difficult at all), and to understand the nuances of connecting to object models for managing the operating system of various types (WMl, ADSl, etc.) and to look for reference information about these objects in external sources.
Also, Windows Script Host is not a command shell, just a scripting environment, so WSH lacks some of the conveniences of the cmd.exe interpreter. For example, to start an external executable utility, it is not enough to simply specify the appropriate file name, you need to use the additional methods pip () and exe ( ) of the WshShe11 object.
WSH script lines cannot be executed line by line interactively. If in cm.exe d you can run separate commands or pipelines from command line commands on the fly and send their output to a text file, then in WSH you need to create a separate file with a script, write the necessary commands there and run the script from the operating system.
Finally, WSH scripts are quite a serious potential security threat, and a large number of viruses are known to use WSH to perform destructive actions.
Although WSH remains a standard component of Windows, VBScript and JScript are now out of favor and are not being developed (the last version of the WSH scripting engine was released in 2006).
Aware of the problems in cmd.exe batch files and Windows Script Host scripts, Microsoft decided to develop a completely new powerful environment for creating scripts and working on the command line. This tool was first publicly introduced in 2003 under the codename Monad, and then renamed PowerShell and has been used in Windows since 2006. In 2017, Microsoft open-sourced PowerShell, now the Orep project
Source (the project repository is on GitHub: https://github.com/PowerShell/ PowerShell). The shell has become cross-platform, you can work with it not only in Windows, but also in macOS and Linux.
Initially, the main and most ambitious goal of the developers of PowerShell was to create an environment for writing and executing scripts that would be best suited for the Windows operating system and would be more functional, extensible and easy to use than any similar product for any other operating system.
First of all, this environment had to be suitable for solving the tasks facing system administrators (thus, Windows would get an additional advantage in the fight for the sector of corporate platforms), as well as meet the requirements of software developers, providing them with the means to quickly implement management interfaces for the applications they create.
About providing direct command-line access to COM, WMI, and .NET Framework objects. PowerShell provides commands that allow interactive work with COM objects, as well as with instances of classes defined in WMl and .NET Framework information schemas;
About the organization of work with ARBITRARY data in the command line according to the principle of the file system. For example, navigation through the system registry or digital certificate store is carried out from the command line using cn1d.exe, an analogue of the CD interpreter command;
Development of an intuitive unified structure of built-in commands based on their FUNCTIONAL purpose. In PowerShell, the names of all internal commands (called cmdlets) follow a verb-noun pattern, such as Get-Process (get information about a process), Stop-Service (stop a service), C1ear-Host (clear the console screen), and so on. As a result, it is easier to remember and learn commands;
About providing the ability to expand the built-in set of commands. PowerShell’s built-in commands can be supplemented with user-created commands that are fully integrated into the shell;
About organizing support for familiar teams from Other shells. In PowerShell, the most commonly used standard shell commands are cmd.exe and UNIX-060 are supported at the alias level of your own internal commands. For example, if the user assigned to work executes the 1s command, he will receive the expected result: a list of files in the current directory (the same applies to the dir command);
About hashing autocompletion when setting shien commands, their parameters, as well as shien veils and folders. This function greatly simplifies and speeds up entering commands from the keyboard.
An interactive session in PowerShell is similar to working in other command line shells. PowerShell is easy to learn and easier to write scripts that access external objects than VBScript or JScript. Special attention was paid to security issues when working with scripts (for example, you can run a script only with the full path to it, and by default PowerShell scripts are generally prohibited from running PowerShell scripts on the system).
The main feature of PowerShell that distinguishes it from all other command line shells is its object orientation. The unit of information processing and transfer in PowerShell is an object (data and own methods), not lines of text, as in other shells. Thanks to this, working in PowerShell becomes easier than in traditional shells, since you do not need to perform additional manipulations to extract the necessary information from the character stream.
To support objects, PowerShell developers decided not to invent anything new and use the unified object model of the .NET Framework. Thus, PowerShell is one of the programming languages (Figure 1.6). At the same time, PowerShell is not like other types of VB.NET or C#, it is a unique language that allows you to combine imperative and declarative programming styles in scripts.
The decision to use the .NET Framework was made for several reasons. First, the .NET Framework is ubiquitous in Windows software development and is, in particular, a common information scheme by which various components of the operating system can interact with each other.
Second, the .NET Framework object model is self-documenting: each . NET-06RkT contains information about its structure. When working interactively, this is very useful, because it becomes possible to execute a request to a specific object directly from the command line and see a description of its properties and methods, that is, to understand what manipulations can be done with this object, without studying additional documentation with its description.
Thirdly, when working in a shell with objects, you can use their properties and methods to easily get the necessary data without parsing and analyzing symbolic information, as is the case in all traditional command shells.
Text lines. Let’s look at an example. Windows has a task list utility that provides information about processes running on the system:
С:\>tasklist Имя образа PID Имя сессии N‘ сеанса Память System Idle Process 0 0 16 КБ System 4 0 32 КБ smss.exe 560 0 68 КБ csrss.exe 628 0 4 336 КБ winlogon.exe 652 0 3 780 КБ services.exe 696 0 1 380 КБ lsass.exe 708 0 1 696 КБ svchost.exe 876 0 1 164 КБ svchost.exe 944 0 1 260 КБ svchost.exe 1040 0 10 144 КБ svchost.exe 1076 0 744 КБ svchost.exe 1204 0 800 КБ spoolsv.exe 1296 0 1 996 КБ kavsvc.exe 1516 0 9 952 КБ kinagent.exe 1660 0 5 304 КБ klswd.exe 1684 0 64 К
Suppose we want to use this utility to determine how much RAM is being used by the kavsvc process in a cmd .exe shell script. eh To do this, select the appropriate line from the output stream of the task1ist command, extract from it the substring containing the required number, and remove the spaces between the numbers (it should be noted that, depending on the settings of the operating system, the number separator may not be a space, but another character).
In PowerShell, a similar problem can be solved using the Get-Process command, which returns a set of objects, each of which corresponds to one running process. To determine the memory consumed by the kavsvc. hehe, there is no need for additional manipulations with the text, you just need to take the value of the ws property of the object corresponding to this process.
Finally, the .NET Framework’s object model allows PowerShell to directly use the functionality of the various libraries that are part of the framework. For example, to find out what day of the week November 9, 1974 was, you can run the following command in a PowerShell shell:
In this case, the Get-Date command is returned. NET-06RkT of type DateTime that has a DayOfWeek property that calculates the day of the week for a given date. Thus, PowerShell developers do not need to create a special library for working with dates and times – they simply take a ready-made solution in the .NET Framework.
The command line and scripts allow you to automate work in the operating system and spend less time on routine operations.
UNIX and Windows operating systems are based on fundamentally different approaches. The principles of UNIX are “everything is a file” and “everything is text”, the principle of Windows is “everything is an object”. Therefore, in systems (macOS, Linux), automation tasks are reduced to file system manipulation and text processing, and to manage Windows, you additionally need to be able to work with internal object models.
Windows has three standard automation tools: the cmd.exe command line and interpreter batch files, Windows Script Host (WSH) scripts in VBScript and JScript, the command line, and the Windows PowerShell scripting environment.
Microsoft has discontinued the development of cmd and WSH, they are supported for the work of previously developed scripts. The main tool now and in the future is PowerShell.
Unlike all other shells, PowerShell commands do not communicate with each other using character strings, but through objects. PowerShell is one of the languages that allows you to combine imperative and declarative programming styles in scripts.
The source code of PowerShe11 is open, the shell is cross-platform, it can be installed on macOS and Linux.
Thanks to our team of volunteers for providing information from open sources.