Installing and configuring Windows PowerShell. Windows PowerShell - Useful Notes Installing powershell

0
Applicable to:
Office 365 for professionals and small businesses, Office 365 for enterprises, [email protected]
Windows XP, Windows Vista, Windows Server 2003, Windows 7 and Windows Server 2008

Before you start using Windows PowerShell, make sure that you have the correct versions of Windows PowerShell and Windows Remote Management (WinRM) installed and configured on your computer. You must use the Windows Management Framework, which includes the correct versions of Windows PowerShell v2 and WinRM 2.0.

If your computer is running Windows 7 or Windows Server 2008 R2, you do not need to install anything. The Windows Management Framework is already installed.

You can download and install the Windows Management Framework if your computer is running one of the following operating systems:

    Windows Vista Service Pack 1 (SP1) or 2 (SP2);

    Windows Server 2008 Service Pack 1 (SP1) or 2 (SP2);

    Windows Server 2003 Service Pack 2 (SP2);

    Windows XP Service Pack 3 (SP3).

Let's get to work:

1. Remove previous versions of Windows PowerShell from your computer

Before installing the Windows Management Framework, you must remove any existing versions of Windows PowerShell.

1.1 Uninstalling Windows PowerShell from Windows Vista

    In the Programs group of the Control Panel, open the Programs and Features section and uninstall any instances of Windows PowerShell that are present in the list of installed programs. For example, the CTP version of Windows PowerShell v2 might appear as "Windows PowerShell (TM) V2".

    In the Tasks section, select View Installed Updates and uninstall any instances of Windows PowerShell that are listed as installed updates. For example, Windows PowerShell V1 might appear as a Windows update with one of the following article numbers in the Microsoft Knowledge Base:

1.2 Removing Windows PowerShell from a Windows Server 2008 system

    Launch Server Manager and open the "Components" section.

    1. Select "Remove Features".

      Select the Windows PowerShell value and follow the instructions to uninstall.

    In the Control Panel, in the Programs group, open the Programs and Features item and uninstall any instances of Windows PowerShell that are in the list of installed programs.

    In the Tasks group, select View Installed Updates. Remove any instances of Windows PowerShell that are listed as installed updates.

1.3 Removing Windows PowerShell from Windows Server 2003 or Windows XP

    Open Add/Remove Programs in Control Panel and uninstall any instances of Windows PowerShell that are listed as installed programs.

    In the Add/Remove Programs section, select Show Updates. Remove any instances of Windows PowerShell that are listed as installed updates. For example, Windows PowerShell V1 might appear as a Windows update with the following article number in the Microsoft Knowledge Base: KB926139.

2. Remove previous versions of WinRM from your computer

You must uninstall any existing versions of WinRM before installing the Windows Management Framework.

2.1 Uninstalling WinRM from Windows Vista or Windows Server 2008

    In the Programs group of the Control Panel, open the Programs and Features section and uninstall any instances of the Windows Remote Control service that are present in the list of installed programs.

    In the Tasks group, select View Installed Updates. Remove any instances of the Windows Remote Control service that are present in the list of installed updates. For example, the CTP version of WinRM 2.0 might appear as "WindowsRemoteManagement" with one of the following article numbers in the Microsoft Knowledge Base:

2.2 Removing Windows PowerShell from Windows Server 2003 or Windows XP

    Open Add/Remove Programs in Control Panel and uninstall any instances of Windows Remote Control that are listed as installed programs.

    In the Add/Remove Programs section, select Show Updates. Remove any instances of the Windows Remote Control service that are present in the list of installed updates. For example, WinRM may appear as a Windows update with the following article number in the Microsoft Knowledge Base: KB936059.

3. Installing the Windows Management Framework

    Download and install the Windows Management Framework. Select the package containing Windows PowerShell v2 and WinRM 2.0 that is appropriate for your operating system, system architecture, and language.

    After installing WinRM and Windows PowerShell, configure the software so that it works correctly as described in the following steps.

Note

4. Checking the ability to run scripts in Windows PowerShell

    Select Start, All Programs, Accessories, Windows PowerShell in sequence.

    To open Windows PowerShell, do one of the following:

    • If you are running Windows Vista, Windows 7, or Windows Server 2008 R2, right-click Windows PowerShell and select Run as administrator. When the User Account Control prompt appears asking you to continue, click the Continue button.

      If you are running Windows XP or Windows Server 2003, click Windows PowerShell.

    Run the following command:

    Get-ExecutionPolicy

    If the value returned is different from RemoteSigned , you must change the value to RemoteSigned .

    Note

    If the script execution policy is set to RemoteSigned , only scripts created on the user's computer or signed by a trusted source can run.

Preparing to Run Scripts in Windows PowerShell

In a Windows PowerShell session opened as an administrator, run the following command:

Set-ExecutionPolicyRemoteSigned

5. Verify that WinRM has permission to connect Windows PowerShell

    Select "Start", "All Programs", "Accessories" in sequence.

    Do one of the following to open a command prompt:

    • If you are running Windows Vista, Windows 7, or Windows Server 2008 R2, right-click Command Prompt and select Run as administrator. When the User Account Control prompt appears asking you to continue, click the Continue button.

      If you are running Windows XP or Windows Server 2003, select Command Prompt.

    At the command line, run the following command:

    winrm get winrm/config/client/auth

    Note

    If the WinRM service is already running, you do not need to start it. The status of the WinRM service can be checked by running the sc query winrm command.

Look for the value Basic = in the results. If Basic = false is specified, then it must be changed to Basic = true .

Note

    If the WinRM service is running and you do not need to change the Basic value, run the net stop winrm command to stop the WinRM service.

Enabling Basic Authentication in WinRM

    In a command prompt window opened as an administrator, run the following commands: The value in curly braces ( ) is case-sensitive:

    winrm set winrm/config/client/auth @(Basic="true")

    Check for Basic = true in the output of the command.

    Note

    If the WinRM service is running, run the net stop winrm command to stop it.

Next action.

Some time has already passed since the launch of the final release of the latest operating system from Microsoft, and not only enthusiasts testing intermediate builds, but also those users who have downloaded the long-awaited update have already managed to get acquainted with it. Is the new system good or not? Is this the latest innovative product or just the G8 that was supposed to come out at the time? These are questions that cannot be answered unambiguously anyway. In addition to the obvious innovations, which include the Start menu that appeared in the system, the Microsoft Edge browser, Xbox compatibility, search and task view integrated with Cortana, there are a number of innovations that not every Windows 10 user knows about.

And one of these innovations is the ability to install software products directly using the Windows PowerShell shell, which will be discussed later in this article. Despite the fact that this functionality appeared back in April 2014, along with the release of Windows Management Framework 5.0 Preview, it could become native only with the final release of the “tens”. So, let's see which module is responsible for this functionality and how you can install software products without downloading installation files.

Windows PowerShell OneGet Module

Since the release of Windows Management Framework 5.0 Preview, Windows PowerShell has several new features designed to make it easier to manage computers. These features include two interesting technologies, namely Windows PowerShell Desired State Configuration and Certified for Windows Network Switches.

In the case of Certified for Windows Network Switches, a number of Windows PowerShell cmdlets have been added that are responsible for managing Windows-certified network switches. That is, there are 19 new cmdlets that you can find by running the “Get-Command *-NetworkSwitch*” command in the PowerShell shell. Since the technology is quite serious and deserves special attention, in this article I will limit myself to only a small description and will not consider this technology in more detail.

But the second technology should be discussed in more detail. If you are installing Windows Management Framework 5 or the Windows 10 operating system, you can use a tool that makes it much easier to find and install software on your computers. OneGet is such a tool. OneGet is a package management aggregator, that is, a module that uses special repositories, providing a single interface for discovering, installing, and inventorying software. In other words, this technology, on the one hand, provides a set of cmdlets that allow the end user to manage installation packages (which we will discuss a little later), and on the other hand, it provides an interface for writing vendor packages.

Before we begin to deal with the module itself, you should pay attention to several definitions that are closely related to this technology, namely:

  • Package. In a nutshell, a package is a program that is built and installed from a specific source using any available package management system. Typically, a package provides compiled code, with additional meta information, which may include a description of the package, its version, or "dependencies". A package management system, for example, to perform an automatic upgrade of a software product to a new version, in order to make sure that all package dependencies will be installed, must process such meta information and, if necessary, must automatically install all missing packages;
  • repository. According to Wikipedia, repositories are places where data is stored and maintained. Most often, the data in the repository is stored in the form of files available for further distribution over the network. Repositories were originally used by Linux systems, allowing you to install packages needed to run the system from other locations. Most repositories are free, but some companies provide access to their own repositories for a paid subscription. We will talk about OneGet repositories a little later;
  • Package Manager. It is a set of software tools responsible for automating the process of installing, updating, configuring and removing software packages. Typically, packages include a database that lists software prerequisites and dependencies, as well as product version information to prevent non-working software products from being used. Package managers include the Linux apt-get or NuGet, which later appeared on Windows systems. In turn, OnetGet is a logical extension of NuGet, acting as an aggregator for all available package managers, called providers.

Initially, Microsoft limits the use of most of the available providers by providing a base set that allows you to discover and install additional providers to manage your software. Key providers include:

  • Bootstrap– a provider that allows other providers to be discovered;
  • MSI– a provider designed to process MSI files;
  • MSU– in turn, the vendor responsible for handling Microsoft update files;
  • ARP(Add/Remove programs) - a provider responsible for inventory data about any software product that is registered in the "Remove or change a program" component of the system;
  • PowerShellGet- A provider that allows you to manage various PowerShell modules.

You can find the full list of OneGet providers with their brief descriptions at the following link.

The OneGet module itself includes 10 Windows PowerShell cmdlets, most of which will be covered in the next section of this article. These cmdlets include:

  • Find-Package - search for packages;
  • Get-Package - returns a list of all packages installed on the computer;
  • Get-PackageProvider - returns a list of providers that are connected to OneGet on this computer;
  • Get-PackageSource - Returns a list of package sources that are registered with a particular package provider.
  • Install-Package - allows you to install one or more software products;
  • Register-PackageSource - adding a package source for the specified package provider;
  • Save-Package - allows you to save the package to the local computer without subsequent installation;
  • Set-PackageSource - change for the specified package provider the source of the package;
  • Uninstall-Package - removal of one or more software packages;
  • Unregister-PackageSource - Remove a registered package source.
    • Installing software using OneGet

      So it's time for the process of installing software products. Next, you will see how you can install a package provider, find the required software, install it, and also how you can remove an unnecessary application and download the installation package of the software product to your computer. Let's start in order.

      Installing the Chocolatey Package Provider

  1. Open Windows PowerShell and to display a list of package sources that are registered with OneGet on the local computer, run the command Get-PackageSource. Note that if you specify a specific package provider in the command, then the Get-PackageSource cmdlet will only show you the sources associated with the provider you specified. Otherwise, the command returns all package sources that are registered with OneGet. Since we need to view the package sources for all providers, the command will run without any additional parameters. Be sure to note that at this stage you have not yet installed an additional package provider that will be used to install software products. You can see the output of the command in the following image:

  2. As you can see in the previous illustration, the Chocolatey provider is not installed on our local machine. Therefore, this needs to be corrected. Note that to add a package provider, PowerShell's ExecutionPolicy must be set to Unrestricted. Otherwise, you will not be able to add the supplier. Let me remind you that the cmdlet Get-ExecutionPolicy allows you to display the execution policies for the current session. The execution policy is part of the Windows PowerShell security policy that determines whether configuration files can be loaded and scripts can be executed, and which scripts require a digital signature to execute. The default value is " Restricted” (does not load configuration files and does not execute scripts), so if you have not changed the value of the execution policy for yourself, run the command Set-Executionpolicy Unrestricted. Since the default scope of the execution policy is LocalMachine, so that the policy settings apply only to the current user, you can add the parameter to the applied command –Scope with meaning CurrentUser. The output of these two commands can be seen in the following illustration:

  3. At this stage, we can see the list of providers that are registered with OneGet on the current computer. To do this, you can use the cmdlet Get-PackageProvider. This cmdlet, as I already mentioned a little above, returns a list of package providers that are already connected to OneGet. Optionally, you can filter the results based on all or part of one (several) vendor names. For example, to see which providers are currently connected, you would run the cmdlet Get-PackageProvider without any additional options. As you can see in the following illustration, initially I had 4 such providers connected to my computer, which I already told you about today. Now, to install the Chocolatey provider on your computer, you need to run the command Get-PackageProvider -Name Chocolatey -ForceBootstrap, where the -ForceBootstrap parameter is responsible for automatically installing the provider. Note that, as a general rule, when you install the Chocolatey provider, the NuGet provider must also be installed. As you can see in the following illustration, after reusing the cmdlet Get-PackageProvider, the provider we are installing should already appear in the list:

Now we can generate a complete list of all packages available in the providers and pipe it to the cmdlet Export-CliXML to create an XML representation of objects and save them in an XML file. Keep in mind that the list you export will be constantly changing and over time more and more packages will be added to the repositories you use. Accordingly, do not forget to replace the file you export from time to time. In order to export the list of packages and save this list in the C:\TestPosh folder, you need to run the following command: Find-Package | Export-CliXML C:\TestPosh\Test.xml

Please note that the export procedure will definitely take you some time. After the command finishes executing and an XML file is created on your computer, import it and, for ease of viewing, using the pipeline and the command gridview, which is responsible for displaying the results of the command in a window in the form of an interactive table, you can see which packages will be available for installation. Naturally, you can open this list of packages using any application that can process XML files, for example, using the same Excel. This command, as you can see in the following illustration, looks like this: Import-CliXML C:\TestPosh\Test.xml | out-gridview

Since the provider is already installed, you can proceed to the next part of this procedure, which is

Installing software using PowerShell

Before installing software products, we should look at what is already installed on the computer. To accomplish this task, you can use the cmdlet Get-Package, which returns a list of all software packages installed on the local machine, either through OneGet or other application installation tools. Optionally, you can also run the cmdlet Get-Package and on remote computers by running it as part of an Invoke-Command, an Enter-PSSession command, or a script.

In the event that you want to get information on specific software, for example, on installed Microsoft Office 2013 products, you can use the –Name parameter along with this cmdlet with the appropriate value, for example, Get-Package -Name "office 2013". The output of this cmdlet is visible below:

Before installing the software, let's try to decide what we need to install. Since only Office 2013 and a few other applications are installed on the machine, next I will show you how you can install software products such as Adobe Creative Cloud, Adobe Reader, Notepad ++, as well as Process Explorer, Process Monitor and WinRar.

Due to the fact that before the installation process itself, we need to localize the packages themselves, we should use the capabilities of the cmdlet Find-Package. As you noted a little earlier, this cmdlet allows you to search for installation packages in the package sources available on the local computer. In the event that you do not use any parameters with this cmdlet, the command will display a complete list of all applications, as was noted earlier.

For example, to begin with, let's try to find Adobe applications that are available for installation from the Chocolatey provider we added. To do this, in addition to the cmdlet itself, it is enough to specify the parameter –Name and enter the desired software product as its value. Because installation packages may have a product name after the word Adobe, enter the product name as follows: Adobe* as shown in the following illustration. As you can see, the OneGet module found the following installation package in the repository: adobe-creative-cloud version 1.0. In principle, this is one of the products you are looking for, which means that it should be installed. To do this, as you can also see in the following illustration, you need to use the capabilities of the cmdlet Install-Package. To install Creative Cloud run the following command Install-Package -Name adobe-creative-cloud –Force, where the Force parameter, as is customary in PowerShell, overrides the restrictions that prevent the command from executing until changes begin to violate security requirements. The output of these commands can be seen in the following illustration:

Now, after the first software product has been installed, let's try to search for a specific version of Adobe Reader. To do this, in addition to the already known command Find-Package –Name AdobeReader parameter should be added –AllVersions, which returns all available versions of a package, or all versions of a package that are in the range specified in the options MinimumVersion and MaximumVersion. Please note that this parameter is optional, since the search initially displays the latest version of the software product. Now, from all the available versions, we should choose the one that should be installed on the computer, for example, let it be the version 2015.007.20033 . in order to install this particular version of the reader, you should for the command Install-Package -Name AdobeReader add parameter –RequiredVersion with meaning 2015.007.20033 , which specifies the exact version of the package you want to install. You can also set the maximum available version of the product by adding the parameter MaximumVersion with the corresponding value. The output of these commands is shown in the following illustration:

If you need to install the latest version of a software product and at the same time don't want to type multiple commands in PowerShell, you can generalize the package search and installation using a pipeline. For example, in the case of installing the latest version of the Notepad++ text editor, you can run the following command: Find-Package -Name NotepadPlusPlus | Install-Package –Force. Thus, you search for a package in the repository and, if you find a result, immediately install it in silent mode. The installation process for this software product is shown below:

Now, since according to the above task, it remains to install Process Explorer, Process Monitor and WinRar, let's try to install several software packages at once. To do this, it is desirable to know exactly how these packages are called in the repository itself. As I wrote earlier, this can be checked using the cmdlet Find-Package | out-gridview. Once the package names are known, you can proceed with the installation itself. To do this, you can run the following command: Find-Package -Name procexp, procmon, winrar | Install-Package. In this example, as you can see in the following illustration, I specifically do not specify the parameter force so that you can pay attention to the whole process of installing several software packages at the same time.

Saving and deleting programs

The last two cmdlets that will be discussed in this article are responsible for saving the installation package and removing the installed program. Let's start with saving.

In order to save the installation package, you can use the next cmdlet of the OneGet module, namely the module Save-Package. This cmdlet allows you to save packages to the local computer without installing them later. By default, this cmdlet saves the latest version of the software product, however, if you add the parameter to the current cmdlet AllVersions, all versions of the program you selected will be saved on your computer. Moreover, similar to the parameters of the search and installation cmdlets, in addition to saving all versions, using the parameters -MaximumVersion and –MinimumVersion, you can also select the version range of the package you wish to keep. To save the package on your computer, in addition to the option name and, if necessary, a parameter that is responsible for the product version, you must specify the parameter path with the future location of your installer.

As you can see in the following illustration, the command Save-Package -Name Procexp -Path C:\TestPosh save the latest version of Process Explorer to the C:\TestPosh folder:

If you accidentally installed the wrong package, you can always remove it using the OneGet module. To do this, use the cmdlet Uninstall-Package. As with the rest of the cmdlets in this module, you need to specify the Name parameter with the appropriate application name to remove the program, and you can also use the Force parameter to remove the program silently. For example, to remove previously installed WinRAR from your computer, you need to run the following command: Uninstall-Package -Name WinRAR -Force as below:

Conclusion

In this article, you learned about one of the features of the new operating system from Microsoft, namely the installation of software products using the Windows PowerShell command shell. I told you about the OneGet module itself, about the basic terminology used along with this technology, and about what pre-installed package providers exist. You learned how you can connect a third-party package provider to OneGet and how you can use it to find, install, save, and remove software products.

I hope that this information was useful for you and you learned something new for yourself. If you have any questions about the material of this article - ask them in the comments, I will be glad to provide any assistance.

VN:F

Rating: 9.9/ 10 (18 votes cast)

Installing programs using PowerShell in Windows 10, 9.9 out of 10 based on 18 ratings

Today I'll show you how to install and use the Active Directory Administration Module for Windows PowerShell. You can use the cmdlets in this module to get information about and manage various AD objects and settings. This module is installed as a separate component in server operating systems. On desktop OSes (Windows 10, 8.1, 7), you will have to install the Remote Server Administration Tools (RSAT) package, which includes a module for interacting with AD from PowerShell. In addition to this module, RSAT includes all the necessary management graphical snap-ins, command-line utilities, and Windows PowerShell modules for Windows and AD administration. You need to download this package for your OS version yourself from the Microsoft website.

Installing the Active Directory Module for Windows PowerShell

The Active Directory Module for Windows PowerShell first appeared in Windows Server 2008 R2. It is automatically set to . To use the PowerShell cmdlets from the AD module, the domain must have at least one controller running Windows Server 2008 R2 or higher. If your network only has Windows Server 2003 and 2008 DCs, you must download and install the Active Directory Management Gateway Service. The PowerShell cmdlets from the Active Directory module interact with a web service that is part of a domain controller with the ADDS role.

You can install the Active Directory Module for Windows PowerShell not only on a domain controller, but on any domain member server or workstation. On Windows Server 2016, you can install the Active Directory Module for Windows PowerShell from the Server Manager graphical console using the Add Roles and Features Wizard. It is enough to start the wizard and at the stage of selecting components, select Remote Server Administration Tools -> Role Administration Tools -> AD DS and AD LDS Tools -> Active Directory Module for Windows PowerShell(Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools ->Active Directory module for Windows PowerShell).

This module can also be installed using PowerShell. Open a PowerShell console with administrator rights and run the commands:

Import-Module ServerManager
Add-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

In Windows 10, Windows 8.1 and Windows 10, to install the RSAT-AD-PowerShell module, you must first install the appropriate version of RSAT, after that the module must be enabled in the Control Panel (Control Panel -> Programs -> Programs and Features and click "Turn on Windows Features" -> Remote Server Administration Tools -> Role Administration Tools -> AD DS and AD LDS Tools -> enable the Active Directory Module for Windows PowerShell component.

Or you can install the module using PowerShell:

Enable-WindowsOptionalFeature -Online -FeatureName RSATClient-Roles-AD-Powershell

Importing and Using the Active Directory PowerShell Module

On Windows 7 and Windows Server 2008 R2 with PowerShell 2.0 installed, to start using the AD module, you need to import it into your PowerShell session with the command:

Alternatively, you can export a module from a remote machine where it is already installed and import it into your PowerShell session:

$MySession = New-PSSession -ComputerName MyDomainController
Export-PSsession -Session $MySession -Module ActiveDirectory -OutputModule RemoteADPosh
Remove-PSSession -Session $MySession
Import-Module RemoteADPosh

In Windows Server 2012 R2/2016 and Windows 8.1/Windows 10, the module (if installed) is automatically imported into the session.

If the computer is joined to a domain, a drive is created by default named AD:..You can navigate to this disk with the CD command and use the familiar file system commands to navigate this disk. Paths are in X500 format.

PS C:\> cd AD:
PS AD:\>dir

PS AD:\> cd "DC=vmblog,DC=ru"

You can display a list of available module cmdlets for working with Active Directory as follows:

Get-Command -Module ActiveDirectory

Different versions of Windows have a different number of cmdlets available:

  • Windows Server 2008 R2 - 76 cmdlets.
  • Windows Server 2012 - 135 cmdlets
  • Windows Server 2012 R2 / 2016 - 147 cmdlets.

So now you can use PowerShell cmdlets to administer AD. On our sites you can get acquainted with the use of the following cmdlets from the AD module for PowerShell: , .

Windows PowerShell is a command-line shell and scripting language with great power and beautiful syntax for system administration. Windows PowerShell is an excellent tool for managing and automating the administration of the Windows operating system, as well as applications that run on Windows.

I was an ardent admirer of vbs-scripts. Since I noticed that for those tasks for which I previously used Delphi, the vbs scripting language is quite suitable. After all, it's much more convenient to just open a notepad, put a few lines there, save the file with the desired extension and run the script. To do this, you do not need to install anything, such as Delphi, which is also paid.

Although vbs is not bad, its successor PowerShell has much more functionality.

I have a vbs script that automatically posts images to one of the blogs. There was a need to align the image in width or height, depending on the resolution of the added image. And so I could not get the resolution of images using a vbs script, but through PowerShell this is done very simply.

If a Starting with Windows 7, PowerShell comes bundled with Windows itself, then in Windows XP you need to download and install it - download PowerShell V2 for Windows XP SP3.

The 5th version of Powershell can be downloaded from the link: microsoft.com, it also describes which file for the desired OS to download and how to install.

How to allow local PowerShell scripts to run?

By default, Windows will not allow you to run PowerShell scripts due to security reasons. You must allow execution of local scripts. Run the command in the console (it will allow you to run local scripts and downloaded scripts signed with a trusted certificate):

powershell -Command Set-ExecutionPolicy RemoteSigned

Otherwise, when you try to run your script, you will see the following text:

Cannot load file C:\ImageSize.ps1 because scripting is not allowed on this system. Type "get-help about_signing" for more information.
+ CategoryInfo: NotSpecified: (:) , ParentContainsErrorRecordException
+ FullyQualifiedErrorId: RuntimeException

To revert this security policy back, write:

powershell -Command Set-ExecutionPolicy Restricted

To allow running any scripts without signature verification, write:

powershell -Command Set-ExecutionPolicy Unrestricted

If you see the following message when running the script:

Security Warning Run only scripts that you trust. While scripts from the Internet can be useful, this script can potentially harm your computer. Do you want to run \server\scripts\my.ps1? [D] Do not run [R] Run once [S] Suspend [?] Help (default is "D"): d

And if you want to get rid of it, then when you run the script, use the -ExecutionPolicy Bypass parameter

Powershell -ExecutionPolicy Bypass -file "\\server\scripts\my.ps1"

How to run a PowerShell script?

Enter the command on the command line

Powershell -File your-script-name.ps1

Where your-script-name.ps1 is the name of your script. PowerShell script files have *.ps1 extension

Help or assistance with Windows PowerShell

PowerShell has various cmdlets for getting this or that help. But the most important one is: Get-Help

Enter commands in the console:

powershell -command Get-Help

powershell -command Get-Help -?

And get two different descriptions that complement each other on how to use the help.

Help features are quite extensive, with examples and detailed descriptions in Russian. Therefore, you can output it in various formats.

For example:

  • powershell -command Get-Help Get-Help - general help for the Get-Help cmdlet
  • powershell -command get-help Get-Help -examples - examples of how you can use the get-help cmdlet
  • powershell -command get-help Get-Help -detailed - detailed help for the get-help cmdlet
  • powershell -command get-help Get-Help -full - the most complete help on the get-help cmdlet

winintro.ru/windowspowershellhelp.ru/ - help in the form of html-book

Windows Powershell Notes:

Comparison Operators

  • -eq - Equal
  • -ne - Not equal - Not Equal
  • -ge - Greater than or equal - Greater than or Equal
  • -gt Greater than
  • -lt - Less than - Less than
  • -le - Less than or equal - Less than or Equal
  • -like - Wildcard comparison - Use wildcards to match a pattern
  • -notlike - Wildcard comparison - Use wildcards to search for wildcard inconsistencies
  • -match - Regular expression comparison - Use regular expressions to match a pattern
  • -notmatch - Regular expression comparison - Use regular expressions to search for pattern inconsistencies
  • -replace - Replace operator - Replaces part or all of the value to the left of the operator
  • -contains - Containment operator - Determine if the value to the left of the operator contains the value to the right. The result is a boolean value
  • -notcontains - Containment operator - Specifies that the value to the left of the operator does not contain the value to the right. The result is a boolean value

By default, comparison operators are not case sensitive.
For case-sensitive comparison, the command is prefixed with "c". For example, the case sensitive -eq operator is changed to "-ceq".
For an explicit case-insensitive comparison, the command is prefixed with "i". Example: the -replace operator is case-insensitively -ireplace

  • -is - Is a type
  • -isnot - Not a type
  • -as - As type, no error if conversion fails

PowerShell Logical Operators:

  • -and - Both conditions must be true for the expression to be true
  • -or - One or both conditions must be true for the expression to be true
  • -xor - One condition must be true and the second must be false for the expression to be true
  • -not - Specified conditions must evaluate to "false" for the expression to be true
  • ! - The specified condition must evaluate to "false" for the expression to be true

$myVar -is "String" $myVar -eq 123 $myVar -ceq $myVar2 "abcdef" -like "abc*" "abcdef" -replace "dEf","xyz" $myVar1 -is "String" -and $myVar2 -is "Int" (1 -eq 1) -and -not (2 -gt 2)

String Operations

#Split the string by spaces: $string = "Test string" $string.split(" ") $string.IndexOf(" ") #Search $string for the first space # Returns the zero-based index of the first occurrence of PS> "abcdeabcde". indexOf("cde") 2 # Returns the index position from the last occurrence of the specified character PS> "abcdeabcde".lastIndexOf("c") 7 # Returns a substring starting at position 1 PS> "abcdefgh".Substring(1) bcdefgh # Returns a substring starting at position 1 and 4 characters long PS> "abcdefgh".Substring(1,4) bcde # Insert substring from position 0 PS> "abcdefgh".insert(0,"X") Xabcdeabcde # Remove from position 0 length 2 PS> "abcdefgh".remove(0,2) cdeabcde # Object property - string length PS> "abcdefgh".length 8 # Returns True if the string contains the substring "cde" PS> "abcdefgh" .Contains("cde ") True # Returns True if the string starts with the substring "abc" PS> "abcdefgh".startsWith("abc") True # Returns True if the string ends with the substring "fgh" PS> "abcdefgh".endsWith("fgh" ) Tru e # Returns True if the string contains the substring "cde" PS> $"abcdefgh" -like "*cde*" True # Returns an array where "d" is the delimiter PS> "abcdefgh" -split "d" abc efgh # Returns string combined from two ":" - separator PS> "abcdefgh", "xyz"-join ";" abcdefgh;xyz # Returns a string where "abc" will be replaced with "XYZ" PS> "abcdefgh".replace("abc","XYZ") XYZdefgh # Returns a string where characters are converted to UPPER case PS> "abcdefgh".ToUpper( ) ABCDEFGH # Returns a string where characters are converted to lowercase PS> "ABCDEFGH".ToLower() abcdefgh

Predefined Variables

$home– user directory
$NULL- empty
$true- truth
$false- lies
$DebugPreference– “Continue” output debugging, “SilentlyContinue” do not output debugging information. See Write-Debug Command

Working with files

$string | Out-File $file -Append #Append $string with a newline to the file $file $string = get-content -Path $file #Get the contents of the file in $string $file $jokes = ::ReadAllText($file) #read the entire file into one line Test-Path "C:\test.txt" #Check if file exists

Find all files with a specific filename extension in a directory and subdirectories.
Then copy these files to another directory.

$flist = get-childitem e:\doc\* -include *.pdf -recurse $flist | ForEach-Object($_.CopyTo("e:\doc\all_pdf\" + $_.PSChildName)) ls d:\ | ?($_.psiscontainer) | select fullname #Show directories only ls d:\ | ?(!$_.psiscontainer) | select fullname #Show files only $local = Get-Location #Current directory $local.Path # Working directory $local.Drive.Root # Root $local.Drive.Name # Drive letter $local.Drive.Used # Drive used $local .Drive.Free # Free on disk

Displaying the full names of files on drive D: that have changed between June 1, 2014 and September 20, 2014:

Ls d:\ -recurse | ?(!$_.psiscontainer) | select fullname,LastWriteTime | Where-Object ( $_.LastWriteTime -ge "06/01/2014" -and $_.LastWriteTime -le "09/20/2014")

Displaying text on the screen

# text to pay attention to. Highlighted in yellow. Write-Warning("Text needs attention") # Just output text Write-Host("Just text") #enable debug output $DebugPreference = "Continue" # print debug information Write-Debug "Cannot open file." # disabled debug output $DebugPreference = "SilentlyContinue"

Pause for a few seconds

Start-Sleep -s 15 # Pause for 15 seconds

Pause in console until Enter is pressed

Read-Host "Press Enter"

Working with processes

#Task: kill all processes named Notepad # Method #1 get-process Notepad | Stop-Process # Method #2 (Only works with one process) $plist = get-process Notepad $plist.Kill() # Method #3 (same as 2, but all processes) $plist = get-process Notepad $ plist | ForEach-Object ($_.Kill()) #Get processes and their start dates: Get-Process| Format-Table Name,StartTime -AutoSize

Increment

$i++ - at the time of calling i has the old value, but after that it increases by 1++

++$i - at the time of the call, i is incremented by 1

Arrays

$array = 17,15,160 #created an array of three elements $array -contains $element #does the array contain the element $file1 #0th element of the $file1.count array #size of the array #removing the "asdf" element from the array $array = @ ("adsf","adf","erge") $array = $array |? ($_ -ne "adf") #get only unique array elements $a = @(1,2,3,4,5,5,6,7,8,9,0,0) $a = $a | select -uniq #index of first occurrence of element in array $array.indexOf("cde")

If Elseif Else construct

if ($i -eq 0) ( Write-Host("i is zero") ) ElseIf ($i -eq 1) ( Write-Host("i is equal to one") ) Else ( Write-Host("i is not equal to zero or one")

ForEach Loop

$services = Get-Service ForEach ($service in $services) ( $service.Stop() ) 65 #convert ASCII code to character "A" #convert character to ASCII code "Hello" #convert string to ASCII codes

Waiting for any key to be pressed:

$HOST.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown") | OUT-NULL $HOST.UI.RawUI.Flushinputbuffer() $host.ui.RawUI.WindowTitle = "(!LANG:elimS Window Title" #задаем заголовок окна !}

Data Types in PowerShell

The most common types:

Fixed-length string of Unicode characters A Unicode 16-bit character An 8-bit unsigned character 32-bit signed integer 64-bit signed integer Boolean True/False value A 128-bit decimal value Single-precision 32-bit floating point number Double -precision 64-bit floating point number Date and Time Xml object An array of values ​​Hashtable object

There are also built-in constants: $true,$false, $null

Unicode: To encode a Unicode character in a PowerShell string, prefix the unicode with 0x and cast it to System.Char:

PS > 0x263a ☺

Data Type Conversion

To force a conversion to a specific datatype, prefix the value or variable with the type in square brackets, this is known as a Cast operator and forces the chosen datatype:

PS C:\> "0064" 64 PS C:\> $false 0 PS C:\> ("0x" + "FF") 255

Testing DataTypes

PS C:\> 32 -is
True PS C:\> $true -is
True

Functions in Powershell

function elimS ( #a function that has multiple input parameters param($string = "default value", $integer = 7) #input parameters write-host "string = " $string " | integer = " $integer ) elimS # call a function without parameter definitions, the parameters will take the default value $string = "test string" $integer = 911 elimS $string $integer #this is how to call the function correctly - we separate the parameters with a space elimS -integer $integer -string $string #this is also correct $global:var1 = "test" is a global variable, so you can pass the value of variables from functions.

More about how to pass multiple parameters to a function:

Rest

get-host #show powershell version Clear-RecycleBin c: -Force #empty trash Compress-Archive -Path C:\test\* -DestinationPath C:\archive\test1.zip #zip folder Expand-Archive -Path C:\temp \test1.zip "C:\test\New folder\" #unpack archive (Get-CimInstance Win32_operatingSystem).lastbootuptime #show system boot time write-host $sleep_array.GetType().FullName #show variable type switch ($a) ( #case - multiple if 1 ($b = $b+10 ) 2 ($b = $b+20 ) 3 ($b = $b+30 ) 4 ($b = $b+40 ) default ($b = $b+50) ) Get-Content -Path "C:\scripts\test.txt" -Wait #similar to tail in linux

powershell cmdlets

Sort-Object- sorts objects in ascending or descending order based on object property values. You can set one property or multiple properties (sort by multiple keys), and you can choose case-sensitive or case-insensitive sorting. You can also make the Sort-Object cmdlet only display objects with unique values ​​for a particular property.

Copy Item- copies an element from one location in the namespace to another. The Copy-Item cmdlet does not delete items that are copied. The types of elements that a cmdlet can copy are determined by the presence of Windows PowerShell providers. For example, using the cmdlet with the FileSystem provider copies files and folders, while using the registry provider copies registry keys and entries.

Move Item- moves an element, including its properties, content, and child elements, from one location to another. Both given locations must be supported by the same provider. For example, you can move a file or subdirectory from one directory to another, or move a registry subkey from one subdirectory to another. When you move an element, it is deleted in its original location and created in a new one.

Remove-Item- removes one or more elements. This cmdlet is supported by many vendors, so it can remove various types of items, including files, directories, registry keys, variables, aliases, and functions.

Get-ChildItem- Gets elements from given locations. If the element is a container, this cmdlet gets elements from the container, which are called child elements. You can use the Recurse option to retrieve items from all child containers. The location can be a location on the file system, such as a directory, or a location provided by another provider, such as a registry hive or certificate store.

powershell cmdlet options

-ErrorAction- the parameter is present in all cmdlets, allows you to set the action to be performed when an error occurs:

  • Continue - display an error message and continue execution
  • SilentlyContinue - ignore the error and continue
  • Stop - stop execution at the first error
  • Inquire - when an error occurs, prompt what to do next

Example: Copy-Item "d:\test1\klbackup*" "d:\test2\" -ErrorAction stop

-WhatIf- Displays a message that describes the result of the command without actually executing it. Present in all cmdlets.

get-help about_CommonParameters- a description of the parameters that can be used with any cmdlet.

SSH via Powershell

An example of how you can work through SSH:

#install the SSH module, once Find-Module Posh-SSH | Install-Module #Create an SSH session: Import-Module Posh-SSH $ComputerName = "1.2.3.4" $UserName = "ubuntu" $KeyFile = "C:\SSH\key.pem" $nopasswd = new-object System.Security .SecureString $Crendtial = New-Object System.Management.Automation.PSCredential ($UserName, $nopasswd) $SSHSession = New-SSHSession -ComputerName $ComputerName -Credential $Crendtial -KeyFile $KeyFile #Create a shell: $SSH = $SSHSession | New-SSHShellStream # send command $SSH.WriteLine("ifconfig") # read response $SSH.read() #close session: $sshSession | Remove-SSHSession

Teams:

  • Get-SSHTrustedHost - view trusted hosts
  • Get-SSHSession - view a list of open sessions
  • Remove-SSHSession - close session

Note. You can use this module without installing WMF 5.0. The module preview for PS 4.0 and 3.0 is available separately - March 2016, and for more recent ones, search the Download Center for PackageManagement PowerShell Modules Preview .

Installing programs

This example installs four programs and the full set of Sysinternals utilities from the Chocolatey repository. The first three commands are executed once, and the policy change must be confirmed. The fourth command silently installs the listed programs, and the fifth simply saves time.

#Allow installation of signed packages from the Internet Set-ExecutionPolicy RemoteSigned #Set Chocolatey provider Get-PackageProvider –Name Chocolatey -ForceBootstrap #Make Chocolatey trusted Set-PackageSource -Name Chocolatey -Trusted #Install programs Install-Package NotepadPlusPlus, vlc, firefox, filezilla, sysinternals -Verbose -Force -ProviderName chocolatey #Add path to executable files (sysinternals) to PATH setx PATH "$env:path;C:\Chocolatey\bin" -m

The provider downloads to C:\Chocolatey\lib a package based on the chocolateyInstall.ps1 script. It downloads the program installer from the official website to the %temp%\Chocolatey folder and runs it in silent installation mode. The simplest example is Notepad++.

Install-ChocolateyPackage "notepadplusplus" "exe" "/S" "https://notepad-plus-plus.org/repository/6.x/6.9/npp.6.9.Installer.exe"

Program search

There are many programs in the repositories, all the most popular ones are definitely there.

Find-Package "*zip*","*commander*" -ProviderName Chocolatey

Installer types and silent installation keys

  • Windows AutoInstall Site and Software AutoInstall Forum
  • Installing Windows updates via Powershell

    • Download the Windows Update PowerShell Module from the microsoft website.
    • Unpack the archive to the folder %WINDIR%\System32\WindowsPowerShell\v1.0\Modules
    • If you haven't allowed running local scripts yet, then let's do it: "Set-ExecutionPolicy RemoteSigned".
      • You can check with the "Get-ExecutionPolicy" command: it should be "RemoteSigned" instead of "Restricted"
    • Import the downloaded module with the command: "Import-Module PSWindowsUpdate"
    • Ready. Now you can use the commands:
      • View a list of available updates: Get-WUInstall -ListOnly
      • Install all updates without asking for confirmation: Get-WUInstall -AcceptAll
      • Install all updates without asking for confirmation and delay reboot: Get-WUInstall -AcceptAll -IgnoreReboot
      • Install certain updates knowing their number:"Get-WUInstall -KBArticleID KB3066441, KB3078676 -AcceptAll -IgnoreReboot" - now you do not need to go to the microsoft site and download them manually
      • Detailed help for the module: get-help Get-WUInstall -detailed
      • View a list of available updates excluding the "Language packs" category, the "Skype" titles, and the KB3012973 update: Get-WUInstall -NotCategory "Language packs" -NotTitle Skype -NotKBArticleID KB3012973 -ListOnly
      • Install updates excluding category "Language packs", titles "Skype" and update KB3012973: Get-WUInstall -NotCategory "Language packs" -NotTitle Skype -NotKBArticleID KB3012973 -AcceptAll -IgnoreReboot

    Hello. =)
    Another blasphemous article about administering Windows Server is devoted to the initial preparation of the OS for use. Spoiled by the fact that in the basic version of Windows Server with a GUI (Graphical user interface), as well as in Windows Server 2012 Core and higher, Powershell is already installed, I was very puzzled by the fact that in Windows Server 2008R2 Core it does not smell. Because the setup was not very obvious and I had to google and technet, I decided to jot down a little note for the future.

    So, first we will have at our disposal at least PowerShell 2.0 (in fact, this step can be skipped by doing everything described below in cmd, but I started with this). This can be done in two ways: by running the sconfig.cmd utility on the command line or via DISM ( Deployment Image Servicing and Management) there. The first one offers us a pseudo-graphical interface, where under point 4 we will find the opportunity to install PS 2.0.

    Through DISM, this is done as follows:
    dism.exe /online /enable-feature:MicrosoftWindowsPowerShell

    After installing PS, rebooting and having a slightly more adequate tool at our disposal, we will try to update it to the current version. At the time of this writing, it is version 4.0 or preview version 5.0. For me, version 3.0 is the minimum usable version, which already has a lot of cmdlets for managing server roles and resources that are not in the second version. Windows PowerShell 3.0 requires the .Net Framework 4.0 or later to be installed on the system.
    If we try to install .Net 4.0 now, we will find out that for this we need the already installed .Net 2.0, which for some reason is missing in the Server Core edition. It's funny, but out of habit, downloading the installer and running it, we will get a refusal to install and notice that we need to use dism.exe. >_< OK, dism, так dism. Уставливается по аналогии с PS:
    dism.exe /online /enable-feature:NetFx2-ServerCore
    dism.exe /online /enable-feature:NetFx2-ServerCore-WOW64

    The next step is to update the .Net Framework to the latest version. If you want to use Powershell 3.0, install .Net 4.0, and if you want the latest version, you need .Net 4.5.1 and higher. The choice is yours, installation is extremely simple. The catch can only be in getting the installer package - I connected a network drive to the server, on which I uploaded all the installation files; you can use any medium convenient for you.

    So, we have prepared the base for installing PS version 3.0 and higher. The next step is to download the Windows Management Framework installer and install it. Download and run KB2819745 of the architecture we need:

    Traditionally, after installation, we need to reboot, after doing it, we will have PowerShell 4.0 at our disposal.

    By the way, in order to be able to use the Add-WindowsFeature cmdlet (renamed to Install-WindowsFeature in Windows Server 2012) to configure server roles, you will need to install the Server Manager components through the same DISM.EXE. It looks like this:
    dism.exe /online /enable-feature:ServerManager-PSH-Cmdlet s
    In general, I am very spoiled by the latest versions of PS, tk. I took it up after the release of the third version, but as it turned out, dism.exe can also be limited to installing roles. And if you do not know the name of the feature you need, then you can always look at all the available options and their status through the /get-features parameter. But as for me, Get-WindowsFeature is much more informative. =)
    dism.exe /online /get-features vs. Get-WindowsFeature