Powershell examples. Examples of PowerShell scripts for Windows. Permission to share a folder using Windows Powershell

PowerShell Cmdlets for outputting data

Typically, some output is generated during PowerShell. To output this data, there are special Out-cmdlets (cmdlets whose name starts with Out-). When the executable PowerShell command returns data, it is piped to the input of the Out-cmdlet, which processes it and sends it to the output device (to the screen, to a file, to a printer, etc.).

The first example assigns a string object with characters in a string enclosed in quotation marks. The shell does not care if you use the name of a plural variable. Also true for the shell, as it is. However, if a variable contains several values, you can use a special syntax to access only one value.

As a best practice, use quotation marks to delimit a variable if you do not have a specific reason to do it differently. There are three specific examples in which you would like to use double quotes. First, when you need to insert the contents of a variable into a string.

To view these cmdlets, run the following command:

Get-Command -Verb Out

Out-Host

The Out-Host cmdlet serves to display the data on the screen. For example:

Get-Process powershell | Out-Host

However, adding an Out-Host to the end of the command is not necessary. At the end of the pipeline, the default is the Out-Default cmdlet, which redirects everything to the Out-Host. Those. the previous command is equivalent to the command:

Testing the computer with PowerShell

This is a great hint for concatenating strings without having to concatenate them. Finally, use double quotes when the string should contain single quotes. Double quotes contain all the content. Note that only the most external set of quotations, in fact, is important. Single quotes are literal characters. Even a simple string, such as "name", is an object of type "System". Use the period after the variable name to tell the shell: I do not want to access the entire object inside this variable.

Get-Process powershell | Out-Default

which in turn is equivalent to the command:

Get-Process powershell

In fact, the output mechanism is even more confusing. As you remember, the result of PowerShell is objects. Out-cmdlets can not work with any objects, but only with a special type of formatting objects, so when the object is received, one of the Format- * formatting cmdlets is called. The Format cmdlet provides the Out-cmdlet with formatting objects that describe the order in which output is generated, and the Out-cmdlet sends them to the desired device. Those. when executing the command:

After the period, specify a name or method. The names of the methods are always accompanied by a set of parentheses. Some methods accept input arguments, and they are enclosed in parentheses in a comma-separated list. Other methods do not require any arguments, and then the parentheses are empty, but do not forget the brackets.

Line 5 illustrates how to access a method by specifying its name after the period followed by brackets. The period is usually an invalid character in the variable name, because this period means that we want to access the property or method. This means that the second line in the following example does not work as expected.

Get-Process powershell

in fact, the team works:

Get-Process powershell | Format-Table | Out-Host


Although adding the Out-Host to the end of the command is optional, but in some cases convenient. For example, he has a key Paging, with which you can organize paged output:

Useful Windows PowerShell cmdlets

In other words, the parentheses tell the shell to "run this first". The entire expression in parentheses is replaced by all the expression generated from this expression. Here are some examples of reason. Reading this article requires a little effort. Start with the expression in parentheses. And access to the first element of the array is the first service. Since it is followed by a period, we know that we are referring to the method of properties or services, and not to the object of the entire service.

Finally, we can extract only the name of the service. In the second line, the expression in parentheses reads the contents text file. Scope of application - the concept of programming, which acts as a containerization system. The shell supports a hierarchy of areas and has a set of rules that determine how the domains can interact and share information with each other.

Get-Process | Out-Host -Paging


The Out-File cmdlet redirects the output to the specified file, for example:

Get-Process powershell | Out-File proc.txt

By default, the data in the file is overwritten. You can prohibit overwriting an existing file by specifying a key NoClobber, and if you need to add data to an existing file, you can use the key Append, which adds data to the end of the file:

The shell itself is a single region, called a global region. When you run a script, it creates a new scope, and inside it runs a script. Any text created by a script, such as a new variable, is saved as part of the script. It is not accessible by the top-level shell.

When the script finishes execution, its scope is discarded and nothing is created within this scope. For example, create a script that contains the following, and run this script from the console window. After the completion of the script, everything that was created was discarded. Not all in the shell with the installed features. Elements such as modules are processed globally at all times. The script can load the module, and the module will remain loaded when the script finishes.

Get-Process powershell | Out-File proc.txt -Append


You can use abbreviated syntax for output to a file. For example:

Get-Process powershell\u003e proc.txt

or to add to the end of the file:

Get-Process powershell \u003e\u003e proc.txt

Out-GridView

The Out-GridView cmdlet displays the data in a graphical table in which you can filter and sort by the desired characteristic. For clarity, you can specify a key Title, which will be displayed in the header:

That's why Deere worked with a pseudonym when you just entered the script. However, an area can create an element with the same name as an element with a higher-level region. This is what was done for the second time. The scope can be quite confusing when it comes to variables. Typically, a particular application should never refer to elements outside the scope, especially to variables.

Let's look at your basic build scripts, although you can always get additional help in this by reading the appropriate topic "inside the shell". In its full form, it is similar to. If the expression is false, the commands will not be executed. It's really all you need if you build. They work the same way as for building.

Get-Process | Out-GridView -Title processes


Starting the third version of PowerShell Out-GridView supports the key PassThru, allowing to transfer the received data further on the conveyor. For example, you can display a list of processes in the graphics snap-in and select them and send them to the Stop-Process cmdlet, which will stop the selected processes:

They express their expression in parentheses. Only the block associated with the first true expression is executed. Also note how these structures were formatted. You can also see formatting, like some guys do. No matter where you put the keys. However, what matters is that you agree in your placement to make your scripts easier to read. It is also important to step back on the same level, each line inside the keys.

Indenting your code is the recommended basic practice. Otherwise, it will be difficult for you to find the right time by opening and closing keys in complex scripts. Consider this poorly formatted script. It is much harder to read, debug, troubleshoot and support. While space after closing parentheses is optional, this makes it easier to read your script. Reverse code is not required, but it simplifies the following scenario.

Get-Process | Out-GridView -PassThru | Stop-Process


Use the Out-Null cmdlet if you do not want to display output. It sends the received data to the device NULL, i.e. removes them. For example, take this command:

$ process = Get-WmiObject win32_process -Filter "Name = 'Notepad.exe'"
$ process.Terminate ()

The placement of the closing bracket on one line is not necessary for the shell, but it is appreciated by the human eye. Be an organized format, and you will have less problems with your scripts. It is intended to repeat a block of instructions if any condition is true, or until the condition is true. In this version of the construction, the commands in curly brackets are always executed at least once. While the condition is not evaluated until the first run. You can move while, in this case the commands will be executed only if the condition is true.

In addition to the main action (stopping the process), it displays a lot of unnecessary information. To get rid of it, send the output to Out-Null, for example:

$ process.Terminate () | Out-Null

$ process.Terminate ()\u003e $ null


The Out-String cmdlet converts the input data into an array of strings. As a matter of fact, Out-String converts PowerShell objects to strings that can be further treated as plain text (format, search, etc.).

It differs only in syntax. For beginners, it is easy to overestimate this design. The variable name is used to remind us that it contains one or more services. Simply because this plural does not lead to the fact that the shell behaves in a special way. Each time he takes one object from the second variable and puts it in the first variable. Inside this constructor, use the first variable to work with a single object. The third line indicates the period "I do not want to work with the whole object, only one of its members - by the Stop method".

For example, we'll show the process, save it in the variable $ a and look at the data type:

$ a = Get-Process powershell
  $ a.GetType ()

Then we will feed the Out-String contents and save the output to the variable $ b:

$ b = $ a | Out-String
  $ b.Get-Type ()

As you can see from the example, at the Out-String input, the Process data type, and at the String output.


Make sure that this is the only way to accomplish the task. When you need to run the method against a large number of objects, and there is a cmdlet that performs the equivalent action. When you own a lot of objects and you need to perform several sequential actions with respect to each of them. When you have an action that can be performed only against the object at the same time, but the script can work with one or more objects, and you have a way of knowing in advance. Sometimes you can use the structures described here to replace these other designs.

Out-String is fundamentally different from other out-cmdlets. Since the usual out-cmdlets work with the end result of the previous commands, they themselves do not produce any output. That's why the out-cmdlet is usually the last one on the command line, because after it there is nothing left in the pipeline that other cmdlets can work with.

For example, with a cycle that will be executed exactly ten times. It's up to you to choose the best design for doing this job. If you are browsing the Internet for scripts, be prepared to start on any changes. A function is a special type of construction that contains a group of related commands that perform a unique and specific task.

Adding parameters to a script

However, the next line to be executed will be line eight, and this will lead to an error. The script does not contain a function called two. As a result, it exists within the function. Only other functions inside the function, you can see two. Trying to call two from any location will result in an error. It's rare to create a script designed to perform exactly the same thing each time it starts. Most often you will have scripts that contain some kind of variable data or the behavior of variables.

Unlike them, Out-String accepts objects, converts them into an array of strings, and passes them along the pipeline. By default, data is accumulated and returned in one line, but with a key Stream   you can specify output on a separate line for each object.

For example, let's list the system services with all the properties and format it in the form of a table:

PowerShell versus bat

Here is a detailed analysis of how it works. When you do not use parameter names, it's more difficult to be flexible. Also, for someone else, it is more difficult to decipher what you understand, which makes it difficult to solve any problems. The best example is the fifth line. I do not need to remember the order in which they came.

  • Line 4 shows what happens if you are not careful.
  • Probably not.
This allows you to declare a parameter as needed, take an entry about the pipeline, and so on. he is right for comments, should precede this, but no more.

Get-Service | Format-Table -Property * -AutoSize

Since the width of the console is bordered by 80 characters, most of the data will be clipped, which is not very cool.


In order not to trim the output, we will direct it to the Out-String and increase the width:

Get-Service | Format-Table -Property * -AutoSize | Out-String -Width 1024

Note that the last parameter does not have any special instructions, and all three parameters are still displayed in the list, separated by commas. There are many other instructions that you can specify for a parameter that you can read in the help section.

I hope you will learn something new. The first term, which is usually a verb, tells us which type of operation will be performed. The next member is responsible for what it should be. Correct alignment of both elements allows you to easily and intuitively configure the commands appropriate for the situation. However, in comparison with his predecessor, he works somewhat differently. Thanks to this, the result that we get is no longer a simple text. The result of the query, even if it is also represented in text form, is actually an object with its own properties and methods.

Now all the data came to the screen, but it still does not look very good.


Correct the situation by passing the Out-String output to the Out-File cmdlet:

Get-Service | Format-Table -Property * -AutoSize | Out-String -Width 1024 | Out-File service.txt

At the output we get the file with the table of the desired width, and for viewing there is a scrollbar. In this way, you can create and view tables of almost any width.

Thanks to this approach, we can get the value of the attribute without the need for a thorough analysis of the text, which in fact often does not give a satisfactory result. This solution also allows the use of a pipeline to process data in a pipeline.

It simply includes the automatic transfer of parameters from one command to another, making the whole be treated as one command. Therefore, list the elements of the active catalog. It is used to indicate which object has properties and which methods we can use on it. The manual itself allows you to get 4 ranges of information. Basic information is a simple description and presentation of command syntax, examples are a description of the command with examples of applications, detailed information is a description of the command and parameters with examples, full information is complete technical documentation containing syntax description, parameters and their individual characteristics and examples. The simplicity of building functions and modules allows you to create your own solutions, depending on the individual needs of each administrator.


The Out-Printer cmdlet redirects the output to the printer. For example:

Get-Service | Format-Table -Property * -AutoSize | Out-File service.txt -Width 1024
Get-Content service.txt | Out-Printer

The output is sent to the printer specified in the system by default. To specify an alternative printer, you can use the key Name.

Administration always has a place for creativity. Do you want to do some automation of the routine task? You are welcome! Need to regularly check for activity? No problem! Do you want to process a giant report and display only the actual data? Also possible. All these and many other tasks are best solved using scripts, and the PowerShell language in the case of Windows is the best choice.

What is PowerShell and why is it good?

Users of UNIX and Linux, and from some point and macOS have got used to the fact that there is always a Bash at hand - a bit old-fashioned, but universal and powerful tool, with which you can create amazing things with just a couple of lines. You register a new script in cron - and it's ready, it's already running on your computer or on the server and quietly doing something useful.

Returning to Windows (and without it sometimes sometimes), you understand that scripts.bat though are good, but they are not always saved: their capabilities are very limited. And if you still believed that PowerShell - this is an unknown thing, for which you need something to raise and adjust, then do not rush to conclusions - it, if you understand, is not bad at all.

Windows PowerShell is an extensible open source automation tool that consists of a shell ( command line) and the scripting language. It was first shown in 2003 (then it was called Monad). PowerShell 2.0 was released as part of Windows 7 and Windows Server 2008 R2 and has since been present in Windows as a standard component. It's even included in Windows XP SP3. PowerShell is built on the .NET Framework and integrated with it. PowerShell can access COM, WMI and ADSI, and, of course, executes console commands.

In general, the "tailor" has strong connections with Microsoft products, whether it's Active Directory or the Exchange mail server. This allows you to access the server snap-in without having to connect to them through the console and give commands.

If before you were not interested in PowerShell, then, most likely, you have the second version. I recommend upgrading to at least the third - it contains much more features and useful chips. If you do not go into details, PowerShell 2.0 includes about a dozen modules and about 350 commands, and in PowerShell 3.0 there are about 2300 cmdlets from more than 70 modules. "Hacker" also wrote about what distinguishes the newest PowerShell fifth version from Windows 10.

Choose a development environment and tools

Now let's figure out where it's best to write code. You can, of course, and in Notepad, Notepad ++ or Sublime. But this in this case is not the most competent choice of the editor. It's best to start acquaintance with PowerShell, armed with the bundled ones.



It's not even an editor, it's almost a full development environment. Here is the function IntelliSense, which allows you to view the list of cmdlets and their parameters, variables, utilities and others. Supports snippets, there is the possibility of expanding the function set due to various add-ons. Very useful and the Commands window. In it you can make commands in the visual mode: you select the module, find the necessary cmdlet and set the necessary parameters to it. The resulting command can be copied to the console or executed immediately. In general, a sort of designer for the admin. And of course, there is syntax highlighting, debugger and much more.

Nevertheless, PowerShell ISE also has worthy competitors. One of them - .

PowerGUI is a visual addition to PowerShell. It simplifies the assembly of your own scripts before selecting the necessary cmdlets. You take what you need to solve the problem, and drag the parts of the code until you get the script. One of the main features of PowerGUI is Power Packs, ready-made scripts published by the community of users and laid out in free access. There are simple commands like adding users, and complex ones like controlling switches and virtual machines. All of them are easy to supplement and modify according to needs.



Firms Sapien - more advanced environment, which is designed to jointly develop one project by a large number of participants. If you ever deal with Visual Studio, then I think you'll notice the similarity. Among the useful features of PowerShell Studio are the Ribbon panel, support for remote debugging, and compiler functions that allow you to include scripts in executable files. There is support for different versions of PowerShell.



It is worth mentioning and the Script Browser for Windows PowerShell ISE. This is not a development environment, but it's an interesting tool developed by Microsoft. Script Browser opens access to the database of ready scripts that you can use as samples to write your code. And this thing is able to analyze the code that you are writing, and tells you how to improve it.



A few useful tricks

Having dealt with the editor, you can start writing the code. PowerShell is an uncomplicated language, and I think you'll quickly figure out what's what. The commands here are called cmdlets, and each of them consists of two parts. First, there is an action, for example Get, Set, Add, Invoke, Remove. Then, the action is directed to: Service, VM, AzureAccount, DHCPServerSetting. Each part is separated from the other by a hyphen. It turns out, for example, get-process. This, by the way, is a useful command that displays a list of processes. For example, if we write

get - process BadTh *

we will see something like this:

Handles NPM (K) PM (K) WS (K) VM (M) CPU (s) Id ProcessName

------------------------

28 4 - 210844 - 201128 - 163 25.67 2792 BadThread

Now you can complete the hung process:

You can look recursively, though it's a bit more complicated logic:

You can also run

By the way, to each field in the option box account   or a computer, you can access and read the data. In this way, you can make whole slices. Here, for example, a query based on data on telephone numbers:

Get - AdUser - Filter * - Properties OfficePhone | FT OfficePhone, UserPrincipalName

PowerShell versus bat

Sometimes the problem can be solved both by the old antiquated method, and at powerShell. I recommend not to be lazy and use the PS, if only because you will learn it faster and can apply it in more difficult situations. In addition, you will gradually appreciate its syntax - more elegant and consistent. Here are some examples of how things were done before and how they can be done with PowerShell.

Do you like the article? Share with friends: