Selecting a development environment on PowerShell and writing scripts for Windows

Introducing PowerShell

When you launch PowerShell, you will not initially notice any differences between it and cmd.exe (except that the default background color of the PowerShell window is blue). Moreover, you will soon discover that copy/paste operations in PowerShell are implemented just as badly as cmd.exe. But the first impression of the similarity of these shells, let’s say, does not entirely correspond to reality.

The fact that PowerShell is based on the .NET Framework is its main difference from previous Windows command shells. PowerShell is completely object oriented. The result of running a command in PowerShell is not some “text itself,” but a .NET platform object. This object represents the data itself and has a set of properties and methods inherent to it.

Internal commands (more precisely, command structures) for working with objects in PowerShell are called cmdlets . A special uniform name was invented for them in the form of an action-goal combination. set is used to receive data get ” is used to receive out ” is used to output, etc. The target is the type of object to which the action will be applied. Cmdlets can be thought of as mini-programs that run in PowerShell. To increase functionality, you can create your own cmdlets or install third-party cmdlets. In addition to cmdlets, PowerShell allows you to run functions, external scripts (stored in files with the ps1 extension), and external executables.

PowerShell includes a fairly extensive help system. To get started with it, you can run the Get-Help command.


To obtain detailed help for a cmdlet or basic information section, you must specify its name as a command parameter.

How to start Windows PowerShell

After explaining what Windows PowerShell is, let's see how to launch it.

  1. On your computer keyboard, press the Win key (this is the key with the Windows logo) and R at the same time. The Run command window will open.
  2. In the Open: box, type powershell and click OK.

A more modern way - available in Windows 10 - is to right-click on the Start menu and select the appropriate option from the Power User menu.

Options

Strictly speaking, in the spirit of consistent naming in PowerShell, all parameter names passed to a cmdlet must follow the "-" character. However, for ease of writing, the names of some parameters can be omitted. For example, to access help for the Get-Content cmdlet instead of specifying the full

Get-Help –name Get-Content

you can enter the command

Get-Help Get-Content

The parameter may have any value (in the example just given, the value of the name parameter was Get-Content) or may not have any value. In this case, it is analogous to a switch for some functionality of the command. For example, if you want to get complete information about the Get-Content cmdlet, enter

Get-Help Get-Content –Detailed

Working with services and processes

PowerShell, of course, can manage services and processes in Windows; for this there are cmdlets such as:

  • Get-Process – displays information about running processes on the computer;
  • Start-Process – starts one or more processes on the computer;
  • Stop-Process - stops one or more running processes;
  • Get-Service – displays information about services;
  • Restart-Service – restarts the service;
  • Start-Service – starts the service;
  • Stop-Service - stops the service;
  • Suspend-Service – suspends the service;
  • Set-Service—Using this cmdlet, you can change the properties of a service, such as description, display name, and startup mode. It can also be used to start, stop or pause a service.

Conveyor

PowerShell implements a mechanism for transferring data from one process to another or outputting it to a file. Since, as noted above, PowerShell operates not with text, but with objects, when redirecting, the element of information exchange is the object, along with its structure. This feature allows you to operate with objects - select them according to a given filter, sort them, group them, etc. To organize such a pipeline (in the documentation in English the term pipeline is used) a vertical bar sign is used in the script text. When such a sign is encountered, the interpreter passes objects from one cmdlet to the other as input parameters.

As an example of a pipeline and the ability to access the properties of objects transferred along it, we give the following situation. To check whether any suspicious programs are running on the computer, we want to get a list of all running processes, get the paths and names of the files that launch them, and also look at the creation date of such files. In addition, we will sort such a list by creation date in descending order and select the 10 most “recent” of them. Let's also add the time of the last modification of the file to the output information. We will exclude processes with the names “System” and “Idle” from consideration, since they do not contain paths to files.

As they say, a well-formulated question is half the solution. Take a look:

Get-Process | where-Object {"System", "Idle" -notContains $_.Name} | Get-Item | Sort CreationTime -desc | Select Directory, Name, CreationTime, LastWriteTime -first 10

When entering code, you can always break the line by placing a `` after a space at the hyphen. You can even just press the Enter key without finishing the line. In this case, PowerShell will change the prompt to >>, letting the user know that the interpreter considers the code incomplete and is waiting for the user to finish typing. Like many other scripting languages, PowerShell allows you to use variables. The variable is denoted by the “$” sign. In the case of transferring an object through a pipeline, the $_ variable points to the transferred object itself.

Let's look at the actions of the code step by step. First, we get the list of processes using the Get-Process cmdlet. This data is passed along the pipeline further and filtered by the conditions specified in where-Object (we discard processes with the names “System” and “Idle”).

The next element of the pipeline, Get-Item, returns the attributes of the selected objects. All that remains is to sort them (time of creation in descending order) and select the values ​​that interest us (names of the folder and executable file, time of creation and last modification of the file). The last parameter, -first 10, specifies that only the first 10 elements from the list of objects will be displayed. Let's try to do:


Wonderful, just what we need. However, when I tried to run the same code in Windows XP or Server 2003, I discovered that it didn't look as smooth there:


When viewing execution results

Get-Process | Select Path

It turned out that PowerShell interprets the paths of two processes - winlogon and csrss - in Windows XP and Server 2003 as \??\C:\WINDOWS\system32\. For an explanation of this behavior, I turned to Vasily Gusev, a PowerShell specialist. He explained that these processes do not use Win32API, and the different response to them in XP/Vista by .NET is likely due to the difference in the platforms of these operating systems.

Having decided that using error handling mechanisms (in terms of bypassing an “incomprehensible” path and suppressing the output of an error message) or excluding winlogon and csrss processes from the list in this case is not suitable (perhaps they are infected, and we no longer show the date of their modification in the results we'll see), the commands were changed as follows:

Get-Process | ForEach-Object { if ($_.Path -ne $NULL ) { Get-Item ($_.Path -replace "\\\?\?\\", "") } } | Sort CreationTime -desc | Select FullName, Name, CreationTime, LastWriteTime -first 10

And the reader can get some insight into the use of conditions and regular expressions in PowerShell. Small explanations to the code. The second stage of the pipeline uses the ForEach-Object cmdlet to perform a specified operation on each object in the set passed to its input. As stated above, the current object on which the operation is being performed is represented by the variable $_. The specified operation here is a condition of the form if (condition){executable code if the condition is true}. Just like in cmd.exe, comparison operators do not use symbols like < or >, but abbreviations - in this case it is “not equal”: -ne. So, if the process path contains any value (in the case of “System” and “Idle” there is simply no path), using the replace function all the “\??\” characters in the path will be removed (perhaps, we will touch on the issue of regular we won't use expressions for now), and the Get-Item cmdlet will provide access to the properties of the current process. Well, then everything is the same as in the first example. The execution result is now the same:

Some useful tricks

Having figured out the editor, you can start writing code. PowerShell is not a complicated language, and I think you'll get the hang of it quickly. The commands here are called cmdlets, and each of them consists of two parts. First comes the action, for example Get, Set, Add, Invoke, Remove. Then it indicates what the action is aimed at: 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. Let's say, if you 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

Getting information about objects

Perhaps the reader has already had a question - how, generally speaking, can you find out what information can be obtained as a result of executing a particular command? What actions can be performed with the received data? For example, in the above case, how would we know that we would be able to get the creation date of the file? One simple way to analyze the object returned by a command is to pass that object as input to the Get-Member cmdlet. This cmdlet displays information about the type of an object and all its elements. As a rule, objects have a large number of different properties and the result of Get-Member can be very voluminous text that is not very convenient to view. In this case, you can either divide the information into parts or filter it. An example of obtaining information about an object returned by the Get-Process cmdlet, which can be viewed page by page:

Get-Process | Get-Member | Out-Host-Paging

When the page is full, the user can choose one of the options - display another page, display another line, or stop displaying data. Data filtering is performed using the MemberType parameter, which determines what type of information should be displayed. For example, the command

Get-Process | Get-Member -MemberType Properties

will display only the properties of the object, and

Get-Process | Get-Member -MemberType Methods

- only his methods. Another way to view the properties of an object is to assign an object to a variable, then type the name of the variable into the console, put a period and press the Tab key. With each keystroke, PowerShell will iterate and substitute the object's methods and properties. Iteration in the opposite direction is possible using the key combination Shift+Tab.

Background execution of tasks

Windows PowerShell has a background execution feature, which is a mechanism by which you can run a command (for example, one that takes a long time to execute) in the background, i.e. after launch, you return to the current session and can continue working without waiting for the command to finish. You will need this feature when you need to run a command that takes quite a long time to complete, and as you know, during this time the PowerShell session is blocked until the command completes, and you need to continue working.

You can manage all the tasks that are running in the background, for example, view the list of tasks, stop the task, delete the task, and, of course, view the result of the task.

Windows PowerShell has the following cmdlets for working with background jobs:

  • Start-Job – start a background task;
  • Stop-Job – stop a background task
  • Get-Job – view the list of background tasks;
  • Receive-Job – view the result of a background task;
  • Remove-Job – remove a background task;
  • Wait-Job – move a background task to the foreground in order to wait for it to finish.

To run in the background, you need to write the Start-Job command, and in curly braces {} a command or set of commands that need to be executed in the background.

For example, let's run some task (show list of services) in the background, then look at the list of background jobs and display the result of our task (i.e. list of services).

Run a task in the background

1 Start-Job{Get-Service}

We look at the list of tasks running in the background

1 Get-Job

Displaying the result of Job1

1 Receive-Job Job1

As you can see, we now have a task with the “Completed” status, i.e. it has already completed (Get-Service just works quickly).

In order to see the result of the background task, i.e. cmdlet Get-Service, we executed the Receive-Job command and passed it the job name (an identifier value is also possible). As a result, we displayed a list of services.

Safety

As already noted, the use of VBScript/JScript scripts poses a potential danger to the system - to execute them, just click on the icon with the mouse. The danger is even greater if the user is logged in with an account that is a member of the Administrators group. In PowerShell, a script with the ps1 extension cannot be executed using the mouse - on the system, such a file will be opened not in the command shell, but in Notepad. To run the script, you need to launch PowerShell itself, enter the file name and press Enter.

In the new shell, substitution of commands is also impossible. The essence of this technique used by attackers is as follows. Typically, a non-administrator user has some folders with write and execute permissions on files. A typical example is the C:\Documents and Settings\username folder. The malware creates an executable file in such a folder with a name that matches the name of the shell command or the name of the executable system program. For example, I created ipconfig.vbs in “my” documents folder, which displays a simple message. Now, if, having launched cmd.exe, and being in my folder, I try to execute the Windows ipconfig command, I will get this result:


To complete the illustration, you can place the executable file in the documents folder, renamed in our case to ipconfig.exe. Then, even when called with an extension, the file will be launched from the current folder, and not from \system32. This trick will not work with PowerShell - to call a script whose path does not coincide with the paths specified in the %Path system variable, you must explicitly specify its location. Even if the script is located in the folder that is the current one for the shell, you must specify the path in the following form: .\file_name. A period with a backslash points the interpreter to the current folder.

Another security mechanism is the script execution policy. Initially, the shell is configured so that even if the script is called correctly, its execution will be prohibited, and the user will receive a corresponding message. The execution policy can be switched to one of four modes:

  • Restricted - default setting, running any scripts is prohibited
  • AllSigned — scripts that have a digital signature from a trusted publisher are allowed to run; User-created scripts must also be certified by a certificate authority
  • RemoteSigned - scripts are allowed to run if they are not trusted but were created by a local user; scripts downloaded from the Internet that do not have a signature will not be executed
  • Unrestricted - any scripts are allowed to run

You can find out the current policy mode by running the Get-ExecutionPolicy command in the shell. To change the mode, run the Set-ExecutionPolicy command with the desired policy name as a parameter.

Also, among the tools that help improve security when working with PowerShell, I would include command parameters from the “what will happen if...” category. There are two of them - whatif and confirm. The first allows you to determine what action will be performed and with what object, but the action itself will not be implemented. Something like a simulation. The second one will ask the user for confirmation before executing the action, and if the answer is yes, it will actually run the required command. That is, this type of insurance.

I will give perhaps the most striking and fun example of using these parameters. If the user tries to run the command:

Get-Process | Stop-Process

then after a few seconds a blue screen with STOP will await him. PowerShell, as follows from the text of the command, will sequentially begin to “kill” all processes running in the system, which will lead to its critical stop. If you run:

Get-Process | Stop-Process -whatif

nothing bad will happen - PowerShell will simply show what it would do if the command were executed without the -whatif switch:

Let's start the research

At first glance, the command shell syntax seems a little confusing, but in reality everything is clear and logical. The names of cmdlets are standardized, the names look like “action-object”. So, to get object data, use the action “Get-*”, set “Set-*”, stop – “Stop-*”, output – “Out-*”, etc. A list of all available commands can be viewed by running "Get-Command". To get help, dial “Get-Help”. For example, let's look at the list of processes, sort them by CPU time usage in descending order and select the 10 most voracious:

PS> Get-Process | Sort CPU -Descending | Select -First 10

It's simple! Let's try to extinguish the most CPU-hungry process:

PS> Get-Process | Sort CPU -Descending | Select -First 1 | stop-process

To find out which drives are available, enter:

PS>Get-PSDrive

Please note that the list will also include the HKCU and HKLM registry branches, which can be accessed as if they were a regular disk:

PS> cd HKLM: PS HKLM>

Now you can navigate the selected branch, view, create and delete objects. for PowerShell , and if you don't want to reinvent the wheel, it's natural to look at the work of other administrators. PowerShell community has created a repository of PoshCode Cmdlets, which is a kind of analogue of Perl CPAN. Here you can find solutions for almost all cases. For example, do you need a PowerShell ? Nothing could be easier! Download the Get-Packet.ps1 file from the site and run:

PS> Get-Packet.ps1 -Statistics

All parameters are described inside the file. Another cmdlet, Analyze-Packet, will allow you to get detailed statistics on packages.

By default, scripting is disabled in PowerShell , so not all commands will run. You can view the current status of the execution policy with the command:

PS> Get-ExecutionPolicy AllSigned

There are four types of policies:

  • Restricted - execution of individual commands is possible, scripts are prohibited;
  • AllSigned - execution of signed scripts is allowed, confirmation is requested before launching;
  • RemoteSigned - similar to the previous one, does not request execution of scripts signed by a trusted publisher, does not require a signature for local scripts;
  • Unrestricted – you can run unsigned scripts.

PS> Set-ExecutionPolicy RemoteSigned

Nicknames

The shell has a built-in mechanism for command aliases. On the one hand, aliases are used to simplify command entry. Typically, in this case, the abbreviated name of the cmdlet is used as the alias (for example, gc for Get-Content or fl for Format-List). On the other hand, this mechanism ensures compatibility of interfaces of different command interpreters. For example, having experience with cmd.exe, you are used to displaying the contents of a folder using the dir command. Running this command in PowerShell will produce the same result, although the shell will actually run the Get-ChildItem cmdlet instead of the dir alias. A list of all available aliases can be obtained using the Get-Alias ​​command. The user can create their own aliases using the Set-Alias ​​command.

What is Windows PowerShell ISE

Windows PowerShell ISE (Integrated Scripting Environment) is an application introduced in PowerShell 2.0. It allows you to run commands and write, test, and debug scripts in a single Windows-based graphical user interface.

This ISE includes a command panel, one for scripting and one for output. The Output Pane displays the results of commands run in the other two panes. In addition, the graphical environment can be changed by selecting the location of the blocks.

PowerShell ISE supports multi-line editing, syntax coloring, TAB completion, and selective execution, and uses its own profile, different from the one used to customize PowerShell.

PowerShell drives

Just as Windows deals with data using the file system, PowerShell works with data stores represented as disks. The physical disks of the system are not the only type of storage built into the shell with which interaction is ensured. The user can work with the registry, built-in and environment variables, and certificate stores in the same way as with regular drives, folders, and files. The implementation of such interaction and the provision of abstractions that allow the user to apply the same commands and methods to different data stores is performed by providers - .NET programs.

The list of providers currently available to the shell can be obtained with the Get-PSProvider command. Initially, PowerShell contains the following “drives” - aliases (Alias), environment variables (Env), physical system drives (C, D, etc.), functions, system registry, internal variables (Variable) and certificate store.

Here is an example of reading the contents of the registry hive HKLM\Software\Microsoft


As you can see, the same commands were used as to obtain information about the file system. But the structure of the data obtained is naturally different. In addition to the name and properties, the subsection number (SKC) and record number (VC) are displayed for each element. Using PowerShell, a user can view registry information and add, delete, and modify keys. Let me give you something like a cheat sheet for working with registry elements:


And code for an example of performing various manipulations with registry keys and their parameters:

# Create a new subsection with the name valks in the branch HKEY_CURRENT_USER\Software New-Item -path HKCU:\Software\valks # Add a new string parameter to the created section with the name Param1 and the value StringValue New-ItemProperty -path HKCU:\Software\valks -name Param1 -propertyType String -value StringValue # Create a SubFolder subsection New-Item -path HKCU:\Software\valks\SubFolder # Add another parameter - Param2 of type DWord and value 12 New-ItemProperty -path HKCU:\Software\valks -name Param2 -propertyType DWord -value 12 # Get a list of all parameters Get-ItemProperty HKCU:\Software\valks # Get the value of the Param2 parameter Get-ItemProperty HKCU:\Software\valks | Format-list Param2 # Or we can read the section into the variable $key $key = Get-ItemProperty HKCU:\Software\valks # And output the value of the desired parameter Write-Host "Value of the Param2 parameter: " $key.Param2 # Change the value of the Param2 parameter to 193 Set-ItemProperty HKCU:\Software\valks -name Param2 -value 193 # Change the name of the parameter Param1 to Parameter1 Rename-ItemProperty -path HKCU:\Software\valks -name Param1 -newname Param1 # Delete Parameter1 Remove-ItemProperty HKCU:\Software \valks -name Parameter1 # Delete the entire subsection valks Remove-Item HKCU:\Software\valks

Here is another small example in the form of a function that searches for programs that automatically load when the system starts. The search scope is defined by an array that includes some known startup points in the registry. The code contains comments, I hope they will explain the essence of the work.

function GetAutoexec ($hives) { # If the function is not given an input array of registry keys, # use this: $hives = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run", ` "HKLM:\SOFTWARE\Microsoft\Windows\ CurrentVersion\Run", ` "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer\Run" # Output the title and move the Write-Host line "Startup list`n" # We begin to iterate through the array elements - registry branches Foreach ($ hive in $hives){ # Display the name of the branch in green Write-Host “Branch $hive” -ForegroundColor Green # Check whether the branch exists in the registry if (Test-Path $hive){ # Get the next registry key [Microsoft.Win32. RegistryKey]$param = Get-Item $hive # for each key... foreach ($p in $param){ # ...get a list of its parameters foreach ($key in $p.getvalueNames()){ # display the name of the parameter and its value “Loading $key from ” + $p.GetValue($key) } } } # wrap the Write-Host line “`n” } } # call the GetAutoexec function itself

The user can create their own disks using existing providers. Here is an example of creating a PowerShell drive named Win, the contents of which will be the root folder C:\Windows:

New-PSDrive -Name Win –PSProvider FileSystem -Root “C:\Windows”

Once a PowerShell disk is created, it can be accessed just like a regular system disk.


However, you should be aware that when you end your PowerShell session, it will be automatically deleted. So are aliases, functions and variables created by the user during the session. In order to save these changes, you need to create a PowerShell profile.

Working with Active Directory

Using cmdlets, you can perform all operations with Active Directory - create, delete, modify, view object properties, move, rename and restore objects, manage groups, FSMO roles, domains and forests, configure policies and much more. AD is accessed through ADSI by querying the "System.DirectoryServices" .NET Framework namespace. But when using ADSI, even simple commands look quite intimidating for beginners (not to mention complex structures). For example, let's set the path to the container and view its properties:

PS> $path = [ADSI]»LDAP://OU=testOU,DC=testdomain,DC=local» PS> $path | Format-List *

To create a new object, type:

PS> $user = $path.Create('user', 'cn= demo')

Win2k8 includes the ADSI Edit utility, which makes it easier to find parameters for writing scripts, and in Win2k8R2 and Win7 (and only in them) a set of AD PowerShell cmdlets (Active Directory Module for Windows PowerShell) is available, with which you can:

  • create, delete, modify, and read objects for users, groups, computers, managed service accounts, and organizational units;
  • manage account properties: expiration date, password, etc.;
  • manage group membership, get a list of groups to which the account is included;
  • manage domain password policy;
  • move domain controllers between sites and obtain information about the domain controller;
  • manage the read-only domain controller password replication policy;
  • manage domains and forests, set the domain and forest functional level.

To install AD PowerShell in Win7, you need to install RSAT (Microsoft Remote Server Administration Tools). After that, AD PowerShell can be downloaded directly from the “Programs and Features” menu (Turn Windows Features on or off - Remote Server Administration Tools - Role Administration Tools - AD DS and LDS Tools - Active Directory PowerShell snap-in). On the Win2k8R2 server, installing the required component is even easier:

PS> Add-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

To load the AD PowerShell module, type:

PS> import-module activedirectory

For example, we get all the CDs of the current domain:

PS> Get-ADDomainController -Filter { name -like "*" }

Cmdlets for working with AD from third-party developers have also appeared. Very popular are the freely available AD PowerShell cmdlets (also called QAD cmdlets) developed by Quest Software. In this set, cmdlet names are composed of a standard action-object pair. In the first position are the same English verbs Get-, Set-, New-, Move-, Remove-, Rename- and so on. On the second - a description of the object with the QAD prefix (-QADUser, -QADComputer, -QADGroup, -QADObject). Getting a list of available QAD cmdlets is very simple:

PS>Get-QCommand

If we are working under a regular account, we will connect to the domain controller as an administrator:

PS> $pw = read-host "Enter password" -AsSecureString PS> Connect-QADService -service 'localhost' -proxy -ConnectionAccount 'testdomain\administrator' -ConnectionPassword $pw

First, we get a list of users and then computers:

PS> Get-QADUser | Get-Member PS> Get-QADComputer

To find out information about an individual user and parameter, simply substitute it in the call:

PS> Get-QADUser Vasja -Properties ManagedObjects

Now let's look at the list of users who have not registered for 2 months and save the output to an HTML file:

PS> $last2months = (Get-Date).AddMonths(-2) PS> Get-QADUser -IncludedProperties LastLogon | where { $_.lastLogon -le $last2months} ​​| Select DisplayName, LastLogon, AccountIsDisabled | ?{-not $_.AccountIsDisabled} | ConvertTo-Html | Out-File c:\report.html

To prevent disabled accounts from being included in the report, the team checked the AccountIsDisabled value. Sign "?" is an alias of "Where-Object"; The special variable "$_", which is often used in PowerShell , points to the current object.

It is worth noting that the LastLogon attribute is not replicated between domain controllers, so if there are several of them on the network, then this value should be obtained from each DC. Let's get a list of CDs and then query each one for LastLogon:

PS> Get-QADComputer -ComputerRole DomainController | foreach { (Get-QADUser -Service $_.Name -SamAccountName username).LastLogon.Value }

Now let’s select all users from the Sales department living in Moscow and specify a new phone number for them:

PS> Get-QADUser -City Moscow -Department Sales | Set-QADUser -PhoneNumber '495-1111111'

Let's create a new domain account:

PS> New-QADUser -name 'user' -ParentContainer 'OU=testOU,DC=testdomain,DC=local' -UserPassword ' [email protected] '

To disable, enable, or unlock an account, use the Disable-QADUser, Enable-QADUser, and Unlock-QADUser cmdlets, respectively. It's also easy to create new objects:

PS> New-QADObject -type OrganizationUnit -ParentContainer teststomain.local -Name NewOU

Now let’s move a number of accounts into the created container:

PS> Get-QADUser -Department Sales | Move-QADObject -To testsdomain.local/Sales

Group management looks similar:

PS> Get-QADGroupMember Scorpio\Managers | where { $_.City -eq 'Ekaterinburg'} | Add-QADGroupMember Scorpio\Ekaterinburg_Managers

when experimenting with PowerShell , so when changing AD objects, it's best to run the execution with the "-whatif" switch. In this case, instead of actually changing the parameters, the script will print to the console whatever it is supposed to do.

PowerShell Profiles

A profile is a file with the extension ps1. In fact, this is the same script executed by the shell when it starts. Profiles in the shell are not created automatically; they must be created by the user himself. The created profiles will be loaded every time PowerShell is launched if the execution policy allows loading configuration files. Up to four different profiles can be processed. The location of the files in the order in which they were downloaded:

  • %windir%\system32\WindowsPowerShell\v1.0\profile.ps1 - profile that applies to all users and shells
  • %windir%\system32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1 - profile that applies to all users of PowerShell only
  • %UserProfile%\My Documents\WindowsPowerShell\profile.ps1 - applies to the current user in all shells
  • %UserProfile%\My Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1 - Applies to the current user only in PowerShell

Under the various shells here, you need to take into account the fact that PowerShell may not be the only application that uses ps1 profile files. Some integrated development environments (IDEs) can also use them. One notable example is the PowerGUI tool developed by Quest Software, which provides a GUI tool for working with PowerShell.

The path to the profile of the current PowerShell-only user is stored in the $profile built-in variable. To create it, run the command:

New-Item -Path $profile -ItemType file -force

Once created, you can open it with any text editor, such as Notepad:

notepad $profile

and make the necessary changes to it. Don't forget to check if the execution policy allows running scripts.

Features of running scripts in PowerShell

It is necessary to mention the features of running PowerShell scripts. This administration and automation tool has very high potential and is a powerful tool, so the developers decided to limit the launch of scripts by default. There are 4 main security policies that govern the launch of scripts on the target device. You can familiarize yourself with them on this slide. Each policy has its own characteristics and applies to different scenarios. In our case, for practical work we will allow the execution of unsigned scripts using the “unrestricted” policy

Working with WMI Objects

WMI (Windows Management Interface, Windows Management Interface) is a set of interfaces for managing Windows OS using special components. It is possible to control a local computer and one located on the network. WMI is a subset of Web-Based Enterprise Management (WBEM) and Common Information Model (CIM) developed by Microsoft. Included in Windows Vista, Windows Server 2003, Windows XP, Windows Me and Windows 2000. Available as a separately installed component for Windows 95 and Windows 98. Supports the use of scripting languages ​​such as VBScript or Windows PowerShell to manage personal computers and servers running Microsoft Windows.

WMI objects are quite native to PowerShell. Just run the command:

Get-WmiObject -List

to see the large number of classes that provide access to WMI objects in the wrapper. If you connect to WMI on a remote computer, the composition of the classes will depend on the OS and the WMI extensions installed on it. To obtain information about available classes on a remote machine, you must specify its IP address or name as a parameter:

Get-WmiObject -List -ComputerName Server

For a successful connection, WMI must be running on the remote computer, and the account used must be a member of the local administrators group.

If you do not use a special instruction, some information is not displayed, apparently for reasons of “not cluttering the screen.” To obtain more detailed information, you can use the formatting and data selection commands.

PS C: \ Documents and Settings \ Administrator> Get -Wmiobject -class Win32_OPERATINGSYSTEM SYSTEMDIRECTORY: \ Windows \ System32 Organization: NRESST BUILDNUMBER: 3790 Registered User: Sergey Serialnumber: 69889-650-3137304-45684 Version: 5.2.3790 PS C: \Documents and Settings\Administrator> Get-WmiObject -Class Win32_OperatingSystem | Format-List Locale, Version, CurrentTimeZone, OSLanguage, InstallDate Locale: 0419 Version: 5.2.3790 CurrentTimeZone: 180 OSLanguage: 1049 InstallDate: 20081022233211.000000+240

And here is a small example of polling all computers on a local network with an address of 192.168.1.0 and a subnet mask of 255.255.255.0:

1..254| ForEach-Object -Process { Get-WmiObject -Class Win32_PingStatus -Filter("Address='192.168.1." + $_ + "'") -ComputerName . } | Select-Object -Property Address,ResponseTime,StatusCode

In the first element of the pipeline, an array of numbers from 1 to 254 is generated. At the second stage, each number from the array is substituted into an IP address that will be pinged using WMI tools. The results will be displayed in a table with three columns - host address, response time and response status. If the host responds, the status code “0” is returned.

Remote control using PowerShell

Windows PowerShell is designed not only for local use, but also for remote command execution. This feature is necessary so that you can control remote computers from your workplace, i.e. run PowerShell commands.

There are several methods of remote control:

  • Using the –ComputerName (many commands have it). In other words, you pass the name of the computer on which you want to execute the command as a parameter. The method has the disadvantage of being limited to the execution of one command;
  • Using sessions. Enter-PSSession cmdlet (interactive session). In this way, you connect to a remote computer and all the commands that you type in PowerShell will be executed on the remote computer in the same way as if you typed the commands directly on the remote computer. The method also has the disadvantage that the session is limited to one computer;
  • Using the Invoke-Command . Using this method, you can run commands or scripts on one computer or on several.

For example, to connect to a remote computer (in the example below ServerName) with an interactive session, run the following command:

1 Enter-PSSession ServerName

INFO

PowerShell is an extensible command-line shell and accompanying scripting language. It simplifies the execution of frequently used tasks, reduces the time required to administer workstations and servers, and also provides the ability to fine-tune Windows OS components.

Today, PowerShell is part of the Win2k8R2 and Win7 operating systems and is built into the graphical administration consoles of recent Microsoft products (such as Exchange 2007 and System Center 2007).

The ADSI Application Programming Interface provides access to Active Directory and allows you to create, modify, delete directory objects, perform searches, and many other operations.

When using QAD, commands for working with AD look much simpler and scripts are more readable.

QAD cmdlets will be needed if you use some GUIs for PowerShell that have a function for working with Active Directory (for example, PowerGUI).

Software manufacturers are not standing aside and are developing a large number of cmdlets.

Rating
( 1 rating, average 4 out of 5 )
Did you like the article? Share with friends:
For any suggestions regarding the site: [email protected]
Для любых предложений по сайту: [email protected]