Installing powershell. Windows PowerShell - Helpful Notes

Some time has already passed since the launch of the final release of the newest operating system from Microsoft and not only enthusiasts testing intermediate builds, but also those users who downloaded the long-awaited update have already become familiar with it. Is the new system good or not? Is this the latest innovative product or just the “eight” that should have come out in due time? These are questions that cannot be answered definitively in any case. In addition to the obvious innovations, which include the “Start” menu that has appeared in the system, the browser Microsoft Edge, compatibility with Xbox, search and task presentation integrated with Cortana, there are a number of other innovations that not everyone knows about Windows user 10.

And one of these innovations is the ability to install software products directly using Windows PowerShell, 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 only become native with the final release of the “ten”. 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

With the release of Windows Management Framework 5.0 Preview, Windows PowerShell now 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 the Certified for Windows Network Switches technology, a number of Windows PowerShell cmdlets have been added that are responsible for managing certified for Windows Network Switches. Windows network switches. That is, there are 19 new cmdlets that you can find by running in the shell PowerShell command"Get-Command *-NetworkSwitch*". Since the technology is quite serious and deserves special attention, in this article I will limit myself to only a short description and will not consider this technology in more detail.

But we should dwell on the second technology in more detail. When Windows installations 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 to provide a single interface for software discovery, installation, and inventory. 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 talk about a little below), and on the other hand, it provides an interface for writing vendor packages.

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

  • Plastic bag. In a nutshell, a package is a program that is compiled 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". Package management system, for example, to automatically update a software product to new version, in order to ensure that all package dependencies will be installed, must process such meta information and, if necessary, must automatically install any missing packages;
  • Repository. According to Wikipedia, repositories are places where data is stored and maintained. Most often, data in a repository is stored in the form of files that are available for further distribution over the network. Repositories were originally used by Linux systems to allow packages needed to run the system to be installed from other locations. Most repositories are free, but some companies provide access to their own repositories for paid subscription. We'll talk about OneGet repositories a little below;
  • Package Manager. It is a set of software tools responsible for automating the process of installing, updating, configuring and uninstalling software packages. Typically, packages include a database that specifies software prerequisites and dependencies, as well as product version information to prevent the use of broken software. Package managers include Linux apt-get or NuGet, which later appeared on Windows systems. In turn, OnetGet is a logical extension of NuGet, working as an aggregator for all available package managers, called providers.

Microsoft initially limits the use of most available providers by providing a basic set that allows you to discover and install additional providers to manage your software. Among the basic suppliers are:

  • Bootstrap– a supplier that allows you to discover other suppliers;
  • MSI– a provider designed to process MSI files;
  • M.S.U.– in turn, the supplier responsible for processing Microsoft update files;
  • ARP(Add/Remove programs) – a supplier 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.

Full list of OneGet providers with their brief description you can find in the following link.

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

  • Find-Package – searching for packages;
  • Get-Package – returns a list of all packages installed on the computer;
  • Get-PackageProvider - returns a list of providers that are on this computer connected to OneGet;
  • Get-PackageSource - Returns a list of package sources that are registered for a specific 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 a package to your local computer without subsequent installation;
  • Set-PackageSource – change the package source for the specified package provider;
  • Uninstall-Package – removal of one or more software packages;
  • Unregister-PackageSource – removes a registered package source.
    • Installing software using OneGet

      Now the time has come for the software installation process itself. Next, you will see how you can install the package provider, find the required software, install it, and also how to remove it 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 run the command to display a list of package sources that are registered with OneGet on your local computer Get-PackageSource. Note that if you specify a specific package supplier in the command, the Get-PackageSource cmdlet will only show you sources that are associated with the supplier you specified. Otherwise, the command returns all package sources that are registered with OneGet. Since we need to view package sources for all providers, the command will be executed without any additional parameters. Be sure to note that at this stage you have an additional package provider that will be used to install software products that has not yet been installed. 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 execution policies for the current session. Execution policy is part of Windows PowerShell's security policy that determines whether configuration files can be loaded and scripts can be executed, and which scripts require execution. digital signature. The default value is " Restricted"(does not load configuration files and does not execute scripts), so if you have not changed the execution policy value, run the command Set-Executionpolicy Unrestricted. Since the default execution policy scope is LocalMachine, so that the policy settings apply only to the current user, you can also add a parameter to the command you apply –Scope with meaning CurrentUser. The output of these two commands can be seen in the following illustration:

  3. At this point, we can see the list of suppliers that are registered with OneGet on the current computer. To do this you can use the cmdlet Get-PackageProvider. This cmdlet, as I mentioned a little above, returns a list of package providers that are already connected to OneGet. You can optionally filter results based on all or part of one(s) of the vendor name(s). For example, to see which providers are connected to this moment, you must run the cmdlet Get-PackageProvider without any additional parameters. As you can see in the following illustration, initially I had 4 of these 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 automatic installation supplier. Note that typically, when you install the Chocolatey provider, the NuGet provider must also be installed. As you can see in the following illustration, after using the cmdlet again Get-PackageProvider, the supplier we install should already appear in the list:

Now we can generate full list all packages available in the providers and pass it along the pipeline to the cmdlet Export-CliXML to create an XML representation of objects and save them in an XML file. Please note 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, remember to replace the file you export from time to time. In order to export a 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 has finished executing and an XML file has been created on your computer, import it and, for ease of viewing, using the pipeline and command GridView, which is responsible for displaying the results of command execution in the 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 is capable of processing XML files, for example, using the same Excel. This command, as you see in the following illustration, looks like this: Import-CliXML C:\TestPosh\Test.xml | Out-GridView

Since the provider has already been installed, you can move on to the next part of this procedure, namely

Installing software using PowerShell

Before installing software products, we should look at what is already installed on the computer. To perform this task, you can use the cmdlet Get-Package, which returns a list of all software packages installed on the local computer, 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 case you want to obtain information on specific software, for example, on installed products Microsoft Office 2013, you can use the –Name parameter with the appropriate value along with this cmdlet, 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, then 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 we need to localize the packages themselves, we should use the capabilities of the cmdlet Find-Package. As you already noticed a little earlier, this cmdlet allows you to search for installation packages in package sources available on the local computer. If 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, first let's try to find Adobe applications, which 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. Since installation packages may have a product name after the word Adobe, you should enter the product name as follows: Adobe*, as shown in the following illustration. As you can see, the OneGet module detected 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 can also be seen 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 common in PowerShell, overrides 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 Adobe versions 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 parameters 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 select 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, follow 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 product by adding a parameter MaximumVersion with the corresponding meaning. The output of these commands can be seen in the following illustration:

If you need to install the latest version of a software product and at the same time do not 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 text editor Notepad++ 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 advisable to know exactly what 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 names of the packages 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 entire process of installing multiple 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 deleting 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 on your local computer without installing them later. By default, this cmdlet saves the latest version of the software product, but 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 install programs cmdlets, in addition to saving all versions, using the parameters -MaximumVersion And –MinimumVersion, you can also select the range of package versions you want to keep. To save the package on your computer, in addition to the option Name and, if necessary, a parameter 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 will save the latest version of Process Explorer in the C:\TestPosh folder:

If you accidentally installed the wrong package, you can always use the OneGet module to remove it. The cmdlet is used for this Uninstall-Package. As with the rest of the cmdlets in this module, to remove a program you need to specify the Name parameter with the corresponding application name, and also, for silent removal, you can use the Force parameter. 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

From 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, the basic terminology used along with this technology and what pre-installed package providers there are. You learned how you can connect a third-party package provider to OneGet and how it can help you find, install, save, and uninstall software.

I hope that this information was useful for you and you learned something new for yourself. If you have any questions about the material in 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

0
Applicable to:
Office 365 for professionals and small businesses, Office 365 for enterprises, Live@edu
Windows XP, Windows Vista, Windows Server 2003, windows 7 and Windows Server 2008

Before you start using Windows PowerShell, you should ensure that the correct versions of Windows PowerShell and Remote Services are installed and configured on your computer. Windows management(WinRM). 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 don't 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 SP1 or SP2;

    Windows Server 2008 SP1 or SP2;

    Windows Server 2003 SP2;

    Windows XP with Service Pack 3 (SP3).

Let's get started:

1. Remove previous versions of Windows PowerShell from your computer

Before installing the Windows Management Framework, you must uninstall all existing versions of Windows PowerShell.

1.1 Removing Windows PowerShell from Windows Vista

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

    In the "Tasks" section, select "View installed updates" and remove all instances of Windows PowerShell that are in the list of installed updates. For example, Windows PowerShell V1 may appear as a Windows update with one of the following article numbers in the Microsoft Knowledge Base:

1.2 Removing Windows PowerShell from Windows Server 2008

    Launch Server Manager and open the Components section.

    1. Select "Remove Features".

      Select Windows PowerShell and follow the removal instructions.

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

    In the "Tasks" group, select the "View installed updates" item. Remove all instances of Windows PowerShell that are in the list of installed updates.

1.3 Removing Windows PowerShell from Windows Server 2003 or Windows XP

    Open Add or Remove Programs in Control Panel and remove any instances of Windows PowerShell that are in the list of installed programs.

    In the Add or Remove Programs section, select Show updates. Remove all instances of Windows PowerShell that are in the list of installed updates. For example, Windows PowerShell V1 may appear as a Windows update with the following article number in the Microsoft Knowledge Base: KB926139.

2. Removing previous versions of WinRM from your computer

Before installing the Windows Management Framework, you must uninstall all existing versions of WinRM.

2.1 Removing WinRM from Windows Vista or Windows Server 2008

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

    In the "Tasks" group, select the "View installed updates" item. Remove all instances of the Windows Remote Management service that are in the list of installed updates. For example, the CTP version of WinRM 2.0 may 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 or Remove Programs in Control Panel and remove all instances of Windows Remote Control that are in the list of installed programs.

    In the Add or Remove Programs section, select Show updates. Remove all instances of the Windows Remote Management service that are 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. Install the Windows Management Framework

    Download and install the Windows Management Framework. Select a package that contains 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. Verify that scripts can run in Windows PowerShell

    Sequentially select “Start”, “All Programs”, “Accessories”, Windows PowerShell.

    To open Windows PowerShell, do one of the following:

    • When working in Windows system Vista, Windows 7 or Windows Server 2008 R2 click right click Click "Windows PowerShell" and select "Run as administrator". When a User Account Control prompt appears asking you to continue, click Continue.

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

    Run the following command:

    Get-ExecutionPolicy

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

    Note

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

Preparing to Run Scripts in Windows PowerShell

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

Set-ExecutionPolicy RemoteSigned

5. Checking whether WinRM has permission to connect to Windows PowerShell

    Sequentially select “Start”, “All Programs”, “Accessories”.

    Do one of the following to open 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 a User Account Control prompt appears asking you to continue, click Continue.

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

    At the command prompt, 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. You can check the status of the WinRM service by running the sc query winrm command.

In the results, look for the value Basic = . If the value 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 net stop winrm to stop the WinRM service.

Enabling Basic Authentication Support in WinRM

    In a window opened as administrator command line 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 command output.

    Note

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

Next action.

Windows PowerShell is a powerful command line shell and scripting language designed for system administration. Windows PowerShell is an excellent tool for managing and automating the administration of the Windows operating system, as well as applications running under Windows.

I was an ardent fan of vbs scripts. Because 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 notepad, throw a few lines there, save the file with the required 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 broader functionality.

I have a vbs script that automatically publishes 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 the images using a vbs script, but this is done very simply through PowerShell.

If 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 to download for the desired OS and how to install it.

How to allow local PowerShell scripts to run?

By Windows default will not allow running PowerShell scripts due to security reasons. You must allow local scripts to run. Run the command in the console (it will allow running 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 this text:

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

To change this security policy back, write:

powershell -Command Set-ExecutionPolicy Restricted

To allow any scripts to be run without checking the signature, 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 running the script, use the -ExecutionPolicy Bypass parameter

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

How to run a PowerShell script?

Enter the command at the command line

Powershell -File your-script-name.ps1

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

Windows PowerShell Help or Help

PowerShell has various cmdlets for getting specific help. But the most important of them is: Get-Help

Enter the commands in the console:

powershell -command Get-Help

powershell -command Get-Help -?

And you will receive two different descriptions that complement each other on how to use the help.

The help options are quite extensive, with examples and detailed descriptions in Russian. Therefore, you can display 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 to 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 for the get-help cmdlet

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

Notes about Windows Powershell:

Comparison Operators

  • -eq - Equal - Equal
  • -ne - Not equal - Not equal
  • -ge - Greater than or equal - More or Equal
  • -gt - Greater than - More
  • -lt - Less than - Less
  • -le - Less than or equal - Less or Equal
  • -like - Wildcard comparison - Using wildcard characters to match a pattern
  • -notlike - Wildcard comparison - Use wildcard characters to match a pattern
  • -match - Regular expression comparison - Use regular expressions to match a pattern
  • -notmatch - Regular expression comparison - Use regular expressions to find a pattern match
  • -replace - Replace operator - Replaces part or all of the value to the left of the operator
  • -contains - Containment operator - Determines whether the value to the left of the operator contains the value to the right. The result is a boolean value
  • -notcontains - Containment operator - Determines 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 case-insensitive -replace operator would be -ireplace

  • -is - Is a type
  • -isnot - Is 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 - The 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 a string by spaces: $string = "Test string" $string.split(" ") $string.IndexOf(" ") #Look for the first space in $string # Returns the zero-based index of the first occurrence of PS> "abcdeabcde". indexOf("cde") 2 # Returns the index position counted from the last occurrence of the specified character PS> "abcdeabcde".lastIndexOf("c") 7 # Returns the substring starting from position 1 PS> "abcdefgh".Substring(1) bcdefgh # Returns a substring starting at position 1 and 4 characters long PS> "abcdefgh".Substring(1,4) bcde # Inserting a substring from position 0 PS> "abcdefgh".insert(0,"X") Xabcdeabcde # Deleting 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 begins with the substring "abc" PS> "abcdefgh".startsWith("abc") True # Returns True if the string ends with the substring "fgh" PS> "abcdefgh".endsWith("fgh" ) True # 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 a string concatenated from two ":" - delimiter 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 UPPERCASE 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– true
$false– lodge
$DebugPreference– “Continue” displays debug information, “SilentlyContinue” does not display debugging information. See Write-Debug command

Working with files

$string | Out-File $file -Append #Append $string with a new line 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 in one line Test-Path "C:\test.txt" #Check file existence

Find all files with a specific extension 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 only files $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 changed in the period from June 1, 2014 to September 20, 2014:

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

Displaying text on screen

# text to pay attention to. Highlighted in yellow. Write-Warning("Text that requires attention") # Just displays text Write-Host("Just text") #enabled debugging information $DebugPreference = "Continue" # displayed debugging 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 the console until you press Enter

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 is increased by 1++

++$i - at the moment of calling i is increased by 1

Arrays

$array = 17,15,160 #created an array of three elements $array -contains $element #does the array contain element $file1 #0th element of the array $file1.count #size of the array #removing element "asdf" 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 the first occurrence of an element in the array $array.indexOf("cde")

If Elseif Else construction

if ($i -eq 0) ( Write-Host("i is zero") ) ElseIf ($i -eq 1) ( Write-Host("i is one") ) Else ( Write-Host("i is not equal 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

We wait for any key to be pressed:

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

Data Types in PowerShell

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 ( #function having several input parameters param($string = "default value", $integer = 7) #input parameters write-host "string = " $string " | integer = " $integer ) elimS #function call without definition of parameters, 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 on how to pass multiple parameters to a function:

Rest

get-host #show powershell version Clear-RecycleBin c: -Force #emptying the recycle bin Compress-Archive -Path C:\test\* -DestinationPath C:\archive\test1.zip #archive the folder Expand-Archive -Path C:\temp \test1.zip "C:\test\New folder\" #unpack the 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 #analogue of tail in linux

Powershell cmdlets

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

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

Move-Item- Moves an element, including its properties, content, and children, 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 you can move a registry subkey from one key to another. When you move an element, it is deleted in its original location and created in a new one.

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

Get-ChildItem- Receives elements from given locations. If the element is a container, this cmdlet retrieves 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 file system location, such as a directory, or a location provided by another provider, such as a registry hive or a certificate store.

Powershell cmdlet options

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

  • Continue - display an error message and continue execution
  • SilentlyContinue - ignore the error and continue
  • Stop - abort execution at the first error
  • Inquire - if an error occurs, display a request for what to do next

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

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

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

SSH via Powershell

An example of how you can work via 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 # sends the command $SSH.WriteLine("ifconfig") # read the response $SSH.read() # close the session: $sshSession | Remove-SSHSession

Teams:

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

Note. You can use this module without installing WMF 5.0. A preview version of the module for PS 4.0 and 3.0 is available separately - March 2016, and search for more recent ones in the download center for PackageManagement PowerShell Modules Preview.

Installing programs

This example installs four programs and a 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 quietly installs the listed programs, and the fifth simply saves time.

#Allow installation of signed packages from the Internet Set-ExecutionPolicy RemoteSigned #Install the 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) in PATH setx PATH "$env:path;C:\Chocolatey\bin" -m

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

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

Search programs

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

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

Types of installers and silent installation keys

  • Windows auto-installation site and program auto-installation forum
  • Installing Windows updates via Powershell

    • Download the Windows Update PowerShell Module from the microsoft website.
    • Unpack the archive into 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 using the "Get-ExecutionPolicy" command: it should be "RemoteSigned" instead of "Restricted"
    • We import the downloaded module with the command: "Import-Module PSWindowsUpdate"
    • Ready. Now you can use the commands:
      • View the 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 postpone reboot: Get-WUInstall -AcceptAll -IgnoreReboot
      • Install specific updates knowing their number:"Get-WUInstall -KBArticleID KB3066441, KB3078676 -AcceptAll -IgnoreReboot" - now you don’t need to go to the microsoft website and download them manually
      • Detailed help on the module: get-help Get-WUInstall -detailed
      • View the list of available updates excluding the "Language packs" category, "Skype" titles and update KB3012973: Get-WUInstall -NotCategory "Language packs" -NotTitle Skype -NotKBArticleID KB3012973 -ListOnly
      • Install updates excluding the "Language packs" category, "Skype" headers and update KB3012973: Get-WUInstall -NotCategory "Language packs" -NotTitle Skype -NotKBArticleID KB3012973 -AcceptAll -IgnoreReboot

    Hello. =)
    Another disgusting article about Windows Server administration is devoted to the initial preparation of the OS for use. Spoiled by the fact that in the basic version of Windows Server with 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 there is no smell of it. Because The setup was not very obvious and I had to surf Google and technet, I decided to jot down a short note for the future.

    So, first we will get at least PowerShell 2.0 at our disposal (in fact, you can skip this step 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 through DISM ( Deployment Image Servicing and Management) in the same place. The first offers us a pseudo-graphical interface, where under point 4 we will find the opportunity to install PS 2.0.

    This is done via DISM as follows:
    dism.exe /online /enable-feature:MicrosoftWindowsPowerShell

    Having installed PS, rebooted and received a slightly more adequate tool at our disposal, we will try to update it to current version. At the time of writing, it is version 4.0 or preview version 5.0. For me, the minimum usable version is version 3.0, which already has many cmdlets for managing server roles and resources that are missing in version 2. Windows PowerShell 3.0 requires the .Net Framework 4.0 or higher on the system.
    If we try to install .Net 4.0 now, we will find out that for this we need already installed .Net 2.0, which for some reason is missing in the Server Core edition. It’s funny, but out of habit, having downloaded the installer and launched it, we will receive a refusal to install and a notice about the 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, but if you want the latest version, you will need .Net 4.5.1 and higher. The choice is yours; installation is extremely simple. The only problem may be in receiving the installer package - I connected to the server network drive, on which I laid out everything setup files; you can use any storage 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 will need a reboot; after completing 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 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'm very spoiled latest versions PS, because... I started working on it after the release of the third version, but as it turned out, you can only use dism.exe to install roles. And if you don’t 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 in my opinion, Get-WindowsFeature is much more informative. =)
    dism.exe /online /get-features vs. Get-WindowsFeature

    Today I will show you how to install and use the administration module Active Directory for Windows PowerShell. The cmdlets in this module can be used to obtain information and manage various AD objects and settings. This module is installed in server operating systems as a separate component. On desktop operating systems (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 graphical management snap-ins, command line utilities and Windows PowerShell modules for administering Windows and AD. 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 installed on . To use PowerShell cmdlets from the AD module, your domain must have at least one controller running Windows Server 2008 R2 or higher. If your network only has DCs running Windows Server 2003 and 2008, you need to download and install Active Directory Management Gateway Service. 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 also on any member domain server or workstation. In Windows Server 2016, you can install the Active Directory module for Windows PowerShell from the graphical Server Manager console by using the Add Roles and Features Wizard. Just run the wizard and at the stage of selecting components you need to 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 which 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

    Import and use the PowerShell module for Active Directory

    In Windows 7 and Windows Server 2008 R2, on which PowerShell 2.0 is installed, to start using the AD module, you need to import it into a 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 imported into the session automatically.

    If the computer is joined to a domain, by default a drive is created by name AD:..You can go to this disk with the CD command and use the usual commands for working with file system to navigate this disc. Paths are presented 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 like this:

    Get-Command -Module ActiveDirectory

    IN different version Windows has 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 website you can get acquainted with the use of the following cmdlets from the AD module for PowerShell: , .