Windows server 2012 установка powershell

top


Mar 14, 2016

Introduction

PowerShell continues to improve, many features are being added and now we have PowerShell 5 that is available for installation on Windows Server 2012 and Windows 8.1. The installation is simple and only requires a reboot. Windows Management Framework 5.0 (WMF 5) includes updates to Windows PowerShell, Windows PowerShell Desired State Configuration (DSC), Windows Remote Management (WinRM), Windows Management Instrumentation (WMI).

Windows Management Framework (WMF) 5.0 RTM brings functionality that has been updated from WMF 4.0. WMF 5.0 RTM is available for installation only on Windows Server 2012 R2, Windows Server 2012, Windows Server 2008 R2, Windows 8.1, and Windows 7 SP1 and contains updated versions or introduction of the following features:

  • Windows PowerShell
  • Just Enough Administration (JEA)
  • Windows PowerShell Desired State Configuration (DSC)
  • Windows PowerShell Integrated Scripting Environment (ISE)
  • Windows PowerShell Web Services (Management OData IIS Extension)
  • Windows Remote Management (WinRM)
  • Windows Management Instrumentation (WMI)

WMF 5.0 RTM replaces the WMF 5.0 Production Preview. You can install WMF 5.0 RTM without uninstalling WMF 5.0 Production Preview, but you must uninstall all other older releases of WMF 5.0 previews before installing the WMF 5.0 RTM.

Process

Download WMF 5 from https://www.microsoft.com/en-us/download/details.aspx?id=50395. There are several packages to choose from for installation.

wmfps5rtm1

Since we are installing on Windows Server 2012 R2 in this example select Win8.1AndW2K12R2-KB3134758-x64.msu or W2K12-KB3134759-x64.msu. For my choice the winner was Win8.1AndW2K12R2-KB3134758-x64.msu. Once downloaded double-click to start the installation and reboot when prompted.

Once the system is back up check the version. Open PowerShell and type $host.version.

PowerShell 5 Propmt

Conclusion

There you have it! Windows PowerShell 5 is now installed and available for you to explore the updated and new features like Windows PowerShell Desired State Configuration (DSC), which we will cover in future posts!

Trackbacks/Pingbacks

top

Обновление

Разберем установку PowerShell версии 5.1, а так же его удаление, на Windows Server 2012
Этому обновлению соответствует KB3191565

По умолчанию в Windows Server 2012 установлен PowerShell версии 3.0

WMF 5.1 в своих пререквизитах не требует установки промежуточных версий, в отличии от упраздненного WMF 5.0.
Поэтому мы сразу можем перейти к установке Windows Management Framework 5.1

Ознакомиться со всеми требованиями к установке можно тут

Откат версии на более низкую

Если у вас есть необходимость вернуться к более низкой версии PowerShell, из-за неправильно выполненной установки,  либо ради проведения тестов, то вы можете попробовать следующий вариант.

Находим список установленных WMF:

Самый быстрый вариант, это использовать скрипт который парсит логи на предмет наличия в них записей о работе с WMF

Показать скрипт поиска обновлений

$Session = [activator]::CreateInstance([type]::GetTypeFromProgID("Microsoft.Update.Session","localhost"))         
$Searcher = $Session.CreateUpdateSearcher()            
$HistoryCount = $Searcher.GetTotalHistoryCount()          
$Searcher.QueryHistory(0,$HistoryCount) | ForEach-Object -Process {            
    $Title = $null            
    if($_.Title -match "\(KB\d{6,7}\)"){            
        # Split returns an array of strings            
        $Title = ($_.Title -split '.*\((?<KB>KB\d{6,7})\)')[1]            
    }else{            
        $Title = $_.Title            
    }                       
    $Result = $null            
    Switch ($_.ResultCode)            
    {            
        0 { $Result = 'NotStarted'}            
        1 { $Result = 'InProgress' }            
        2 { $Result = 'Succeeded' }            
        3 { $Result = 'SucceededWithErrors' }            
        4 { $Result = 'Failed' }            
        5 { $Result = 'Aborted' }            
        default { $Result = $_ }            
    }            
    New-Object -TypeName PSObject -Property @{            
        InstalledOn = Get-Date -Date $_.Date;            
        Title = $Title;            
        Name = $_.Title;            
        Status = $Result;
        Description = $_.Description            
    }            
            
} | ?{ $_.Description -match 'Windows Management Framework'} | ?{ $_.Status -eq 'Succeeded' } | Sort -Property InstalledOn

Еще один способ найти обновление — это использовать командлет Get-HotFix:

Get-HotFix KB3191565

Его минус в том, что он не отображает имя программы к которой относится Update, а так же его точное время установки.

Затем выполняем команду на удаление выбранного KB, соответствующего нужному нам WMF:

wusa /uninstall /kb:3191565

И последним шагом заново выполняем установку PowerShell 5.1

wusa C:\W2K12-KB3191565-x64.msu

Про развертывание PowerShell в домене средствами GPO читайте тут

Записки администратора

Windows PowerShell is a new command-line shell designed especially for system administrators. It includes an interactive prompt and a scripting environment that can be used independently or in combination.

Unlike most command-line shells, which accept and return text, PowerShell is built on top of the .NET Framework common language runtime (CLR) and the .NET Framework, and accepts and returns .NET Framework objects. This fundamental change in the environment brings entirely new tools and methods to the management and configuration of Windows.

Like many shells, Windows PowerShell gives you access to the file system on the computer. In addition, PowerShell Providers enable you to access other data stores, such as the registry and the digital signature certificate stores, as easily as you access the file system.

A cmdlet (pronounced as “command-let”) is a single-feature command that manipulates objects in PowerShell. You can recognize cmdlets by their name format which is verb and noun separated by a dash (-), such as Get-HelpGet-Process, and Start-Service.

In traditional shells, the commands are executable programs that range from the very simple (such as ren.exe) to the very complex (such as netsh.exe).

In PowerShell, most cmdlets are very simple, and they are designed to be used in combination with other cmdlets. For example, the “get” cmdlets only retrieve data, the “set” cmdlets only change data, the “format” cmdlets only format data, and the “out” cmdlets only direct the output to a specified destination.

Each cmdlet has a help file that you can access by typing:

get-help <cmdlet-name> -detailed

The detailed view of the cmdlet help file includes a description of the cmdlet, the command syntax, descriptions of the parameters, and an example that demonstrate use of the cmdlet.

Windows Commands and Utilities

You can run Windows command-line programs in PowerShell, and you can start Windows programs that have a graphical user interface, such as Notepad and Calculator, at the Powershell prompt. You can also capture the text that Windows programs generate and use that text in PowerShell.

For example, the following commands use ipconfig and net commands.

PS C:\Windows\system32> ipconfig

Windows IP Configuration

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::6594:644d:560c:dbfb%15
   IPv4 Address. . . . . . . . . . . : 192.168.4.254
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::ed2:b5ff:fe1f:5174%15
                                       192.168.4.10

Tunnel adapter isatap.{962CC11B-3F41-40C1-8E02-F5CF5976F2D7}:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

PS C:\Windows\system32> net localgroup administrators
Alias name     administrators
Comment        Administrators have complete and unrestricted access to the computer/domain

Members

-------------------------------------------------------------------------------
techtutsonline\surender
localadmin
The command completed successfully.

You can even use PowerShell cmdlets, like Select-String, to manipulate the text that Windows programs return.

For example, the following command uses a pipeline operator to send the results of an ipconfig command to the PowerShell Select-String cmdlet, which searches for text in strings. In this case, you use Select-String to find the pattern “IPv4” in the ipconfig output.

PS C:\Windows\system32> ipconfig | select-string -pattern IPv4

   IPv4 Address. . . . . . . . . . . : 192.168.4.254

When a Windows command or tool has parameters, such as the “-r” (restart) parameter of shutdown command (shutdown -r), PowerShell passes the parameters to the tool without interpreting them.

However, if the tool uses a PowerShell reserved word, or uses a command format that is unknown to it, such as “-D:debug=false” parameter (PowerShell interprets this as two parameters, “-D” and “debug=false”), enclose the parameters in quotations marks to indicate to PowerShell that it should send the parameters to the tool without interpretation.

Processing Objects

Although you might not realize it at first, when you work in PowerShell, you are working with .NET Framework objects. As you gain experience, the power of object processing becomes more evident, and you’ll find yourself using the objects and even thinking in objects.

Technically, a .NET Framework object is an instance of a .NET Framework class that consists of data and the operations associated with that data. But you can think of an object as a data entity that has properties, which are like characteristics, and methods, which are actions that you can perform on the object.

For example, when you get a service in PowerShell, you are really getting an object that represents the service. When you view information about a service, you are viewing the properties of its service object. And, when you start a service, that is, when you change the Status property of the service to “Started,” you are using a method of the service object.

All objects of the same type have the same properties and methods, but each instance of an object can have different values for the properties. For example, every service object has a Name and Status property. However, each service can have a different name and a different status.

When you’re ready, it’s easy to learn about the objects. To find out what type of object a cmdlet is getting, use a pipeline operator (|) to send the results of a “get” command to the Get-Member cmdlet. For example, the following command sends the objects retrieved by a Get-Service command to Get-Member.

PS C:\Windows\system32> Get-Service | Get-Member

   TypeName: System.ServiceProcess.ServiceController

Name                      MemberType    Definition
----                      ----------    ----------
Name                      AliasProperty Name = ServiceName
RequiredServices          AliasProperty RequiredServices = ServicesDependedOn
Disposed                  Event         System.EventHandler Disposed(System.Object, System.EventArgs)
Close                     Method        void Close()
Continue                  Method        void Continue()
CreateObjRef              Method        System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
Dispose                   Method        void Dispose(), void IDisposable.Dispose()
Equals                    Method        bool Equals(System.Object obj)
ExecuteCommand            Method        void ExecuteCommand(int command)
GetHashCode               Method        int GetHashCode()
GetLifetimeService        Method        System.Object GetLifetimeService()
GetType                   Method        type GetType()
InitializeLifetimeService Method        System.Object InitializeLifetimeService()
Pause                     Method        void Pause()
Refresh                   Method        void Refresh()
Start                     Method        void Start(), void Start(string[] args)
Stop                      Method        void Stop()

[output cut]

To find the values of all of the properties of a particular object, use a pipeline operator (|) to send the results of a “get” command to a Format-List or Format-Table cmdlet. Use the Property parameter of the format cmdlets with a value of all (*). For example, to find all of the properties of the Windows Update service on the system, type:

PS C:\Windows\system32> Get-Service wuauserv | Format-List -Property *

Name                : wuauserv
RequiredServices    : {rpcss}
CanPauseAndContinue : False
CanShutdown         : False
CanStop             : False
DisplayName         : Windows Update
DependentServices   : {}
MachineName         : .
ServiceName         : wuauserv
ServicesDependedOn  : {rpcss}
ServiceHandle       : SafeServiceHandle
Status              : Stopped
ServiceType         : Win32ShareProcess
Site                :
Container           :

Remember that PowerShell is not case sensitive. It means cmdlet “Get-Service” and “get-service” will return same result. But you will see PowerShell commands written in PascalCase in many blogs . This is because PowerShell uses TAB key for auto-completion and the TAB key automatically changes the first letter to uppercase. If you type “get-ser” and press TAB key, you will notice that the cmdlet name changes to “Get-Service”. The PascalCase also improves readability.

Object Pipelines

One major advantage of using objects is that it makes much easier to pipeline commands. Pipeline means to pass the output of one cmdlet to another cmdlet as input. In a traditional command-line environment, you would have to manipulate text to convert output from one format to another and to remove titles and column headings.

PowerShell provides a new architecture that is based on objects, rather than text. The cmdlet that receives an object can act directly on its properties and methods without any conversion or manipulation. Users can refer to properties and methods of the object by name, rather than calculating the position of the data in the output.

In the following example, the result of an ipconfig command is passed to a findstr command. The pipeline operator (|) sends the result of the command on its left to the command on its right. In PowerShell, you do not need to manipulate strings or calculate data offsets.

PS C:\Windows\system32> ipconfig | findstr "Address"
   Link-local IPv6 Address . . . . . : fe80::6594:644d:560c:dbfb%15
   IPv4 Address. . . . . . . . . . . : 192.168.4.254

PowerShell System Requirements

When PowerShell was initially started (with version 1.0), it was mainly designed to work with only local computer. The latter version (version 2.0 and above) included the PowerShell Remoting feature which allow the system administrators to run the commands on remote computers and servers.

In this section, I will look into the system requirements for Windows PowerShell 3.0 and Windows PowerShell 4.0, and for special features, such as Windows PowerShell Integrated Scripting Environment (ISE), CIM commands, and workflows.

Windows 8.1 and Windows Server 2012 R2 comes with Windows PowerShell installed by default.

Operating System Requirements

Windows PowerShell 4.0 runs on the following versions of Windows:

  • Windows 8.1, installed by default
  • Windows Server 2012 R2, installed by default
  • Windows 7 with Service Pack 1, install Windows Management Framework 4.0 to run Windows PowerShell 4.0
  • Windows Server 2008 R2 with Service Pack 1, install Windows Management Framework 4.0 to run Windows PowerShell 4.0.

Windows PowerShell 3.0 runs on the following versions of Windows:

  • Windows 8, installed by default
  • Windows Server 2012, installed by default
  • Windows 7 with Service Pack 1, install Windows Management Framework 3.0 to run Windows PowerShell 3.0
  • Windows Server 2008 R2 with Service Pack 1, install Windows Management Framework 3.0 to run Windows PowerShell 3.0
  • Windows Server 2008 with Service Pack 2, install Windows Management Framework 3.0 to run Windows PowerShell 3.0.

Microsoft .NET Framework Requirements

Windows PowerShell 4.0 requires the full installation of Microsoft .NET Framework 4.5. Windows 8.1 and Windows Server 2012 R2 include Microsoft .NET Framework 4.5 by default.

Windows PowerShell 3.0 requires the full installation of Microsoft .NET Framework 4. Windows 8 and Windows Server 2012 include Microsoft .NET Framework 4.5 by default, which fulfills this requirement.

To install Microsoft .NET Framework 4.5  download the file dotNetFx45_Full_setup.exe from Microsoft Download Center.

WS-Management 3.0

Windows PowerShell 3.0 and Windows PowerShell 4.0 require WS-Management 3.0, which supports the WinRM service and WSMan protocol. This program is included in Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows Management Framework 4.0, and Windows Management Framework 3.0.

Windows Management Instrumentation 3.0

Windows PowerShell 3.0 and Windows PowerShell 4.0 require Windows Management Instrumentation 3.0 (WMI). This program is included in Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows Management Framework 4.0, and Windows Management Framework 3.0. If this program is not installed on the computer, features that require WMI, such as CIM commands, do not run.

Windows PowerShell Engine Requirements

Windows PowerShell 4.0 is designed to be backwards compatible with Windows PowerShell 3.0 and Windows PowerShell 2.0. Cmdlets, providers, snap-ins, modules, and scripts written for Windows PowerShell 2.0 and Windows PowerShell 3.0 run unchanged in Windows PowerShell 4.0.

However, due to a change in the runtime activation policy in Microsoft .NET Framework 4.0, Windows PowerShell host programs that were written for Windows PowerShell 2.0 and compiled with Common Language Runtime (CLR) 2.0 cannot run without modification in Windows PowerShell 3.0, which is compiled with CLR 4.0.

The Windows PowerShell 2.0 engine requires Microsoft .NET Framework 2.0.50727 at a minimum. This requirement is fulfilled by Microsoft .NET Framework 3.5 Service Pack 1. This requirement is not fulfilled by Microsoft .NET Framework 4.0 and later releases of Microsoft .NET Framework.

Installing PowerShell on Windows 8 and Windows Server 2012

Windows PowerShell 3.0 arrives installed, configured, and ready to use. Windows PowerShell Integrated Scripting Environment (ISE) is installed and enabled.

Installing PowerShell on Windows 7 and Windows Server 2008 R2

To install Windows PowerShell 3.0

  • Install the full installation of Microsoft .NET Framework 4 (dotNetFx40_Full_setup.exe) from the Microsoft Download Center at http://go.microsoft.com/fwlink/?LinkID=212547. OR, install Microsoft .NET Framework 4.5 (dotNetFx45_Full_setup.exe) from the Microsoft Download Center at http://go.microsoft.com/fwlink/?LinkID=242919.
  • Install Windows Management Framework 3.0 from the Microsoft Download Center at http://go.microsoft.com/fwlink/?LinkID=240290.

    Installing Windows PowerShell on Server Core

    To install Windows PowerShell 3.0

    1. Start Cmd.exe
    2. Run the following DISM commands. These commands install .NET Framework 2.0 and Windows PowerShell 2.0.
      dism /online /enable-feature:NetFx2-ServerCore
      dism /online /enable-feature:MicrosoftWindowsPowerShell
      dism /online /enable-feature:NetFx2-ServerCore-WOW64
    3. Install Microsoft .NET Framework 4.0 full installation for Server Core from the Microsoft Download Center at http://go.microsoft.com/fwlink/?LinkID=248450.
    4. Install Windows Management Framework 3.0 from the Microsoft Download Center at http://go.microsoft.com/fwlink/?LinkID=240290.

    Getting Ready to Use Windows PowerShell

    When Windows PowerShell is installed and started, consider the following setup options. You can perform these tasks at any time.

  • Install help files. The cmdlets that are included in PowerShell 3.0 do not come with help files. However, you can use the Update-Help cmdlet to download and install the newest help files on your computer. When the files are installed, you can use the Get-Help cmdlet to display them right at the command line.
  • Run scripts. To keep PowerShell secure, the default execution policy on PowerShell is Restricted. This policy allows you to run cmdlets, but not scripts. To run scripts, use the Set-ExecutionPolicy cmdlet to change the execution policy to AllSigned, RemoteSigned or Unrestricted. To see the current ExecutionPolicy of system, use Get-ExecutionPolicy cmdlet. Only members of the Administrators group on the computer can run this cmdlet.
  • Enable Remoting. The system is already configured for you to run remote commands on other computers. On Windows Server 2012 R2 and Windows Server 2012, the system is also configured to receive remote commands, that is, to allow other computers to run remote commands on the local computer. To enable computers running other versions of Windows to receive remote commands, run the Enable-PSRemoting -Force cmdlet on the computer that you want to manage remotely. Only members of the Administrators group on the computer can run this cmdlet.

NOTE: If remoting is enabled on a computer that is running Windows PowerShell 2.0, remoting is still enabled after you install Windows Management Framework 3.0. However, on Windows Server 2008 (not Windows Server 2008 R2), you must re-enable remoting after installing Windows Management Framework 3.0.

Back

В этой статье мы рассмотрим, как обновить версию Windows PowerShell до актуальной 5.1 и установить (обновить) PowerShell Core 7.3. В предыдущей статье мы рассказывали, что на данный момент есть две ветки PowerShell:

  • старая версия Windows PowerShell (максимальная версия 5.1, которая более не развивается);
  • новая платформа PowerShell Core (сейчас доступна версия 7.3).

Несмотря на то, что нумерация версий PowerShell продолжается с 5.1 (6.0, 6.1, 7.0 и т.д.), это две разные платформы. Соответственно мы отдельно рассмотрим как обновить Windows PowerShell и PowerShell Core.

PowerShell Core 7.x максимально совместима с Windows PowerShell. Это означает, что вы можете запускать свои старые скрипты и командлеты в PowerShell Core.

Содержание:

  • Обновление Windows PowerShell до 5.1
  • Установка/обновление PowerShell Core 7.x
  • Установка/обновление PowerShell Core на удаленных комьютерах
  • Обновление PowerShell через Windows Update или WSUS

Обновление Windows PowerShell до 5.1

Во всех версиях, начиная с Windows 10 и Windows Server 2016, Windows PowerShell 5.1 уже установлен по-умолчанию.

В предыдущих версиях (Windows 7/8.1 и Windows 2008 R2/2012) обновление до PowerShell 5.1 нужно выполнять вручную. Например, в Windows Server 2012 R2 (Windows 8.1) установлен PowerShell 4.0.

Попробуем обновить версию Windows PowerShell в Windows Server 2012 R2 до версии 5.1.

Сначала проверьте текущую версию PowerShell (на скриншоте видно, что это PowerShell 4.0):

$PSVersionTable.PSVersion

$PSVersionTable.PSVersion версия powershell

Чтобы обновить вашу версию PowerShell до 5.1, нужно установить пакет Windows Management Framework (WMF) 5.1, который в свою очередь требует наличия .NET Framework 4.5.2 (или более поздней версии). Убедитесь, что у вас установлена версий .NET 4.5.2 или выше командой:

(Get-ItemProperty ‘HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full’ -Name Release).Release

проверить версию .net

В моем случае код 378675 говорит о том, что установлена версия .NET 4.5.1. Поэтому мне нужно скачать и установить более новую .NET Framework 4.8 (ссылка на офлайн установщик https://go.microsoft.com/fwlink/?linkid=2088631 —
ndp48-x86-x64-allos-enu.exe
).

Установите .NET 4.8 (потребуется перезагрузка).

офлайн установка .NET Framework 4.8

Если установить WMF 5.1, но не установить .NET 4.5.2 (или более новый), часть функций PowerShell не будет работать.

Скачайте WMF 5.1 для Windows Server 2012 R2 —
Win8.1AndW2K12R2-KB3191564-x64.msu
(https://go.microsoft.com/fwlink/?linkid=839516).

Установите MSU файл Windows Management Framework 5.1.

установка Windows Management Framework 5.1 kb3191564

После перезагрузки сервера, запустите консоль powershell.exe и убедитесь, что версия была обновлена до PowerShell 5.1.

обновление версии windows powershell до 5.1 в windows server 2012 r2

Если у вас остались снятые с поддержки Windows Server 2008 R2 и Windows 7, вы можете обновить на них версию PowerShell с 2.0 до 5.1 аналогичным способом. Сначала устанавливается .Net Framework 4.5.2 (или выше) и затем WMF 5.1 (ссылки загрузки будут другими, чем для Windows Server 2012 R2).

Установка/обновление PowerShell Core 7.x

PowerShell Core является кроссплатформенной и находится в стадии активной разработки (в отличии от Windows PoweShell 5.1). По сути, PowerShell Core это новая платформа, которая устанавливается в операционной системе вместе с классическим Windows PowerShell. Т.е. нельзя обновить PowerShell 5.1 до PowerShell Core 7.1. PowerShell 7 устанавливается на компьютере отдельно от Windows PowerShell 5.1 (side by side).

На данный момент доступны версии PowerShell Core 6.x и 7.x. Рекомендуется всегда устанавливать последнюю версиях PowerShell (сейчас это 7.3), если вам не требуется особая совместимость с legacy скриптами.

Вы можете обновить (установить) версию PowerShell Core в Windows 10 и 11 несколькими способами:

  • С помощью MSI установщика PowerShell Core, который можно скачать на GitHub
  • С помощью менеджера пакетов WinGet
  • С помощью магазина приложений Microsoft

Далее мы рассмотрим все эти способы на примере обновления PowerShell Core до 7.3 в Windows 10 22H2

Обновить PowerShell Core с помощью MSI установщика

Если вы хотите установить PowerShell Core с помощью MSI пакета, перейдите на старицу проекта https://github.com/PowerShell/PowerShell и скачайте установочный пакет для вашей версии ОС. На момент написания статьи последняя версия v7.3.3 Release of PowerShell от 24 февраля 2023 (например, PowerShell-7.3.3-win-x64.msi или PowerShell-7.3.3-win-x86.msi). Для продуктивной среды используйте Stable или LTS релизы.

скачать MSI установщик PowerShell для windows

Скачайте msi файл и установите его.

Доступны следующие опции установки:

  • Add PowerShell to Path Environment Variable
  • Register Windows Event Logging Manifest (для событий PowerShell будет создан отдельный журнал Event Viewer
    %SystemRoot%\System32\Winevt\Logs\PowerShellCore%4Operational.evtx
    )
  • Enable PowerShell Remoting (включает и настраивает WinRM для PowerShell Remoting)
  • Add ‘Open here’ context menu to Explorer
  • Add ‘Run with PowerShell 7’ context menu for PowerShell files

параметры установки powershell из msi пакета

Далее вы можете включить автоматическое обновление PowerShell Core через WIndows Update/WSUS (рассмотрено ниже).

разрешить автоматическое обновление powershell core 7.2+

Для установки PowerShell Core из MSI пакета средствами SCCM/MDT/скриптами в тихом режиме можно использовать команду установки со следующими параметрами:

  • ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL
  • ADD_FILE_CONTEXT_MENU_RUNPOWERSHELL
  • ENABLE_PSREMOTING
  • REGISTER_MANIFEST
  • ADD_PATH
  • DISABLE_TELEMETRY
  • USE_MU – использовать Microsoft Update для получения обновлений PSCore
  • ENABLE_MU – разрешить обновление PowerShell Core через Windows Update

Например, команда установки может выглядеть так:

msiexec.exe /package PowerShell-7.3.3-win-x64.msi /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1 ADD_PATH=1 ENABLE_MU=1 ADD_PATH=1

Вы можете обновить PowerShell непосредственно из консоли. Чтобы установить или обновиться до последней версии PoSh Core, выполните команду:

iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI"

Данная команда загружает установочный MSI файл PowerShell 7.3 с GitHub и запускает установку через MSI Installer.

install-powershell.ps1 скрипт обновления powershell

После окончания установки открывается окно PowerShell Core (pwsh.exe), проверьте версию PowerShell и убедитесь, что теперь это PoSh 7.3.3.

Используем менеджер пакетов WinGet для установки/обновления PowerShell Core

Если у вас установлен пакетный менеджер WinGet, вы можете установить или обновить версию PowerShell до актуальной командой:

winget install --id Microsoft.Powershell --source winget

Либо можно установить конкретную версию PowerShell Core:

winget install --id=Microsoft.PowerShell -v "7.1.2" -e

При использовании менеджера пакетов Chocolatey, используйте команды (для 5.1):

choco install powershell -y
choco upgrade powershell -y

Для обновления PowerShell 7.x:

choco upgrade pwsh -y

Обратите внимание на каталоги различных версий PowerShell:

  • Windows PowerShell 5.1:
    $env:WINDIR\System32\WindowsPowerShell\v1.0
  • PowerShell Core 6.x:
    $env:ProgramFiles\PowerShell\6
  • PowerShell 7.x:
    $env:ProgramFiles\PowerShell\7

Если на компьютере был установлен PowerShell 6.x, то при установке PowerShell 7.3 каталог
$env:ProgramFiles\PowerShell\6
автоматически удаляется.

Обратите внимание, что имя исполняемого файла среды PowerShell изменился. Теперь это
c:\Program Files\PowerShell\7\pwsh.exe
. У него собственная иконка в меню Start.

  • Для запуска Windows PowerShell, основанного на .NET Framework используется команда
    powershell.exe
  • Для запуска PowerShell Core, основанного на .NET Core, нужно использовать команду
    pwsh.exe

powershell core 7 в windows 10

Т.е. теперь на этом компьютере есть две версии: Windows PowerShell 5.1 и PowerShell Core 7.3.

две версии powershell на компьютере core и desktop

Чтобы узнать версию PowerShell можно проверять версию файла pwsh.exe:

(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version

Так можно проверить версию файла на удаленном компьютере:

Invoke-Command -Computername computer1 -Scriptblock {(Get-Command 'C:\Program Files\PowerShell\7\pwsh.exe').Version}

Чтобы запустить предыдущую версию PowerShell (например 4), используйте команду:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Version 4

Установка PowerShell Core через Microsoft Store

В Windows 10 и 11вы можете установить или обновить PowerShell через магазин приложений Microsoft Store. Приложение PowerShell можно найти в магазине вручную, или воспользуйтесь этой ссылкой.

Также вы можете установить магазинную версию PowerShell через WinGet:

winget search powershell --source msstore
winget install --id 9MZ1SNWT0N5D

Преимущество установки PowerShell Core через Microsoft Store в том, что магазин прилжений будет автоматически контролировать установленную версию PowerShell и автоматически устанавливать обновления по мере их появления.

Вы можете проверить, установлена ли у вас Store версия PowerShell Coreс помощью команды:

Get-AppPackage Microsoft.PowerShell

В этом примере пакет Microsoft.PowerShell_7.3.3.0_x64__8wekyb3d8bbwe установлен.

Но есть и недостатки, связанные с тем, что такой PowerShell будет запускаться в песочнице.

ustanovkaобновление powershell core в windows 10 через microsoft store

Установка/обновление PowerShell Core на удаленных комьютерах

Рассмотрим два сценария установки или обновления версии PowerShell Core на множестве компьютерах.

Обновление PowerShell Core с помощью GPO

В домене Active Directory вы можете централизованно установить и обновить PowerShell Core с помощью групповой политики. Воспользуйтесь возможностями установки программ с помощью MSI пакетов в GPO.

  1. Скачайте установочный MSI файл PowerShell и скопируйте его в каталог SYSVOL на контроллере домена;
  2. Откройте консоль управления доменными GPO (
    gpmc.msc
    ), создайте новую GPO и назначьте ее на OU с компьютерами и серверами;
  3. Перейдите в раздел GPO Computer Configuration –> Software Settings, создайте новый пакет и укажите для него путь к установочному MSI файлу PowerShell в SYSVOL;
    обновление powershell в домене через gpo

    Для более тонкого нацеливания политики на клиентов можно использовать WMI фильтры GPO.

  4. Для обновления групповых политик установки ПО нужно перезагрузить компьютеры. Во время загрузки на всех компьютерах будет установлена новая версия PowerShell.

Обновление PowerShell на удаленных компьютерах из командной строки

Вы можете обновлять PowerShell на удаленных компьютерах из командной строки.

  • Первый способ позволяет удаленно обновить PowerShell на компьютере с помощью MSI установщика в сетевом каталоге:
    Invoke-Command -ComputerName dc01 -ScriptBlock {Start-Process msiexec.exe -ArgumentList '/package "\\srv1\share\PowerShell-7.3.3-win-x64.msi" /quiet ADD_EXPLORER_CONTEXT_MENU_OPENPOWERSHELL=1 ENABLE_PSREMOTING=1 REGISTER_MANIFEST=1' -Wait}
  • Следующий скрипт позволит выбрать все активные компьютеры с Windows 10 из домена Active Directory и запустить на каждом из них загрузку и установку PowerShell Core:
    $creds = $(Get-Credential)
    $computers = Get-ADComputer -Filter 'operatingsystem -like "*Windows 10*" -and enabled -eq "true"'
    ForEach ($computer in $computers) {
    Invoke-Command -ComputerName $computer -Credential $creds {iex "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -Quiet"}
    }

Будьте внимательными при использовании команд PowerShell Remoting при подключении к удаленным компьютерам (Enter-PSSession, Invoke-Command). Если вам нужно подключиться к точке управления PowerShell 7 нужно использовать команду:

Enter-PSSession -ComputerName dc01 -ConfigurationName "powershell.7"

Иначе вы подключитесь к точке PowerShell Remoting 5.1.

Обновление PowerShell в Linux дистрибутивах чаще проще всего выполняется через нативный менеджер пакетов.

Обновление PowerShell через Windows Update или WSUS

До версии PowerShell Core 7.2 не поддерживалось автоматическое обновление pwsh.exe. После выхода нового релиза в консоли появилось уведомление:

A new PowerShell stable release is available. Upgrade now, or check out the release page at: https://aka.ms/PowerShell-Release?tag=v7.1.3

Начиная с версии 7.2, PowerShell Core поддерживает автоматическое обновление через Windows Update ( Microsoft Update, Windows Update for Business, внутренний WSUS сервер или SCCM). Для этого при установке MSI пакета нужно включить соответствующие опции.

Проверьте, что в панели управления Settings -> Update and Security -> Windows Update -> Advanced Options теперь включена опция Receive updates for other Microsoft products when you update Windows.

Разрешить Windows получаить обнволения с Windows Update для других продуктов

Теперь, когда вы нажимаете кнопку Check for Updates или запускаете сканирование обновлений через модуль PSWindowsUpdate, вы также будете получать обновления для PowerShell Core.

проверить новые обновления в windows

Running PowerShell scripts on Windows Server 2012 R2 can be a powerful way to automate various tasks and streamline your workflow. PowerShell is a command-line shell and scripting language developed by Microsoft, specifically designed for system administration. In this tutorial, we will guide you through the steps of running PowerShell scripts on Windows Server 2012 R2.

Step 1: Launch the PowerShell Console
Open the start menu and search for “Windows PowerShell.” Click on the PowerShell icon to launch the PowerShell console.

Step 2: Set Execution Policy
By default, the execution policy restricts running PowerShell scripts on a Windows Server. To enable script execution, you need to change the execution policy.

Type the following command in the PowerShell console and press Enter:
“`
Set-ExecutionPolicy RemoteSigned
“`
This command allows the execution of locally created scripts or signed scripts from trusted publishers.

Step 3: Navigate to the Script’s Location
Use the `cd` (Change Directory) command to navigate to the directory where your PowerShell script is located. For example, if your script is in the “C:Scripts” directory, type the following command:
“`
cd C:Scripts
“`

Step 4: Run the PowerShell Script
To run a PowerShell script, type the script’s filename with the “.ps1” extension and press Enter. For example, if your script is named “myscript.ps1,” type the following command:
“`
.myscript.ps1
“`
Press Enter to execute the script. The output of the script will be displayed in the PowerShell console.

Step 5: Execution Policy Changes (Optional)
After running the script, you may want to revert the execution policy to its original state for security reasons. To reset the execution policy to its default value, type the following command and press Enter:
“`
Set-ExecutionPolicy Restricted
“`
This command restores the default execution policy, which only allows the execution of PowerShell commands.

Pros Cons
1. Allows automation and scripting of various tasks. 1. Executing scripts without proper understanding can pose security risks.
2. Provides greater control and flexibility compared to GUI-based tools. 2. Writing scripts may require learning PowerShell syntax and commands.
3. Scripts can be reused and shared across multiple machines. 3. Debugging scripts can be more challenging compared to GUI-based tools.

Video Tutorial: How to install PowerShell 2.0 on Windows Server 2012 R2?

Where is PowerShell in Windows Server 2012?

In Windows Server 2012, PowerShell is a powerful command-line shell and scripting language that is built on top of the .NET framework. Its primary function is to automate administrative tasks and provide a more efficient way to manage and control the server environment.

To locate PowerShell in Windows Server 2012, you can follow these steps:

1. Click on the “Start” button or press the Windows key on your keyboard to open the Start Menu.

2. In the Start Menu, locate the “Windows PowerShell” folder. It is usually found in the “Windows Administrative Tools” section. You can either scroll through the list or use the search bar to find it quickly.

3. Click on the “Windows PowerShell” folder to expand it.

4. Within the folder, you will find two options: “Windows PowerShell” and “Windows PowerShell ISE” (Integrated Scripting Environment). The former represents the standard PowerShell command-line interface, while the latter offers an enhanced scripting environment with additional features like syntax highlighting and debugging.

5. Choose the appropriate option depending on your needs. If you’re just starting with PowerShell, the standard command-line interface should suffice.

By following these steps, you will be able to locate and access PowerShell in Windows Server 2012, allowing you to leverage its powerful features for system administration and automation tasks.

How do I enable PowerShell script on server?

To enable PowerShell script on a server, you need to follow these steps:

1. Open PowerShell as an administrator: Right-click on the Start menu button and select “Windows PowerShell (Admin)” from the context menu.

2. Check the Execution Policy: Run the command `Get-ExecutionPolicy` to see the current execution policy. By default, it is likely set to “Restricted,” which prevents the execution of PowerShell scripts.

3. Change the Execution Policy: To allow script execution, run the command `Set-ExecutionPolicy RemoteSigned`. This execution policy only allows the execution of scripts signed by trusted publishers. However, it allows the execution of local scripts without requiring a digital signature.

4. Confirm the execution policy change: After setting the execution policy, run `Get-ExecutionPolicy` again to verify that it shows “RemoteSigned.”

5. Run PowerShell scripts: Now, you can run PowerShell scripts on the server. To execute a script, open PowerShell, navigate to the script’s location using the `cd` (change directory) command, and then run the script using its file name and extension (e.g., `.scriptName.ps1`).

By following these steps, you can enable the execution of PowerShell scripts on your server without any security or permission issues. However, always exercise caution when running scripts from untrusted sources or those you have not thoroughly reviewed.

Is PowerShell 5.0 is included with Windows Server 2012 R2?

Yes, PowerShell 5.0 is included with Windows Server 2012 R2. It was released as part of the Windows Management Framework (WMF) 5.0 update, which included updates to PowerShell, Windows Management Instrumentation (WMI), and the Server Manager CIM Provider.

Here are the steps to verify that PowerShell 5.0 is included with Windows Server 2012 R2:

1. Open the Start menu or press the Windows key on your keyboard.
2. Type “PowerShell” in the search bar and open the “Windows PowerShell” or “Windows PowerShell ISE” application.
3. Once the PowerShell console or ISE opens, type the following command and press Enter:
“`
$PSVersionTable.PSVersion
“`
4. The output will display the version of PowerShell installed on your system. If it shows as 5.0 or higher, then PowerShell 5.0 is included with Windows Server 2012 R2.

Note: PowerShell versions can also be checked from the “Programs and Features” section in the Control Panel of Windows Server 2012 R2. Look for “Windows Management Framework 5.0” or “Windows Management Framework 5.1” under the installed programs list to verify the installed version of PowerShell.

What version of PowerShell is available for Windows 2012 R2?

PowerShell is a powerful task automation and configuration management framework developed by Microsoft. When it comes to Windows Server 2012 R2, it includes a pre-installed version of PowerShell. Here’s the version information.

Windows Server 2012 R2 comes with PowerShell version 4.0 by default. PowerShell 4.0 introduced several new features and enhancements over its predecessor, such as Desired State Configuration (DSC), enhanced debugging capabilities, and improved language support.

To verify the installed PowerShell version on Windows Server 2012 R2, you can follow these steps:

1. Launch PowerShell: Click on the Start button or press the Windows key, type “PowerShell,” and click on “Windows PowerShell” from the search results.
2. Run the command: In the PowerShell window, type the following command and press Enter:
`$PSVersionTable.PSVersion`

This command will display the PowerShell version information, including the major version, minor version, build version, and revision.

Please note that while PowerShell version 4 is the default version on Windows Server 2012 R2, it is possible to upgrade PowerShell to a newer version manually if desired. However, this answer is based on the assumption that the server is running the default configuration without any additional updates or modifications.

To run a PowerShell script from the Command Prompt (cmd), you can follow these steps:

1. Open the Command Prompt: Press the Windows key, type “Command Prompt,” and click on the application when it appears in the search results.

2. Navigate to the directory containing the PowerShell script: Use the “cd” command to change the directory to where the script is located. For example, if the script is located in “C:Scripts,” type `cd C:Scripts` and press Enter.

3. Run the PowerShell script: Once you’re in the correct directory, you can execute the PowerShell script by entering the following command:

“`
powershell -File scriptname.ps1
“`

Replace “scriptname.ps1” with the actual name of your PowerShell script, including the file extension.

4. Press Enter to run the command, and the PowerShell script will execute.

By following these steps, you’ll be able to run PowerShell scripts directly from the Command Prompt, allowing you to automate various tasks or perform specific operations easily.

How to open PowerShell ISE in Windows Server 2012 R2?

To open PowerShell ISE (Integrated Scripting Environment) in Windows Server 2012 R2, you can follow these steps:

1. Launch the Start Menu: Click on the Windows logo located in the bottom-left corner of your screen or press the Windows key on your keyboard.
2. Search for PowerShell ISE: Begin typing “PowerShell ISE” in the search bar. As you type, the search results will start appearing.
3. Open PowerShell ISE: Once you see “Windows PowerShell ISE” in the search results, click on it to open the application.

Alternatively, you can also use the Run dialog box to open PowerShell ISE:

1. Press the Windows key + R on your keyboard simultaneously. This will open the Run dialog box.
2. In the Run dialog box, type “powershell_ise” (without quotes) and press Enter or click on the OK button.

By following these steps, you should be able to open PowerShell ISE on Windows Server 2012 R2.
{“@context”:”https://schema.org”,”@type”:”FAQPage”,”mainEntity”:[{“@type”:”Question”,”name”:”Where is PowerShell in Windows Server 2012?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”In Windows Server 2012, PowerShell is a powerful command-line shell and scripting language that is built on top of the .NET framework. Its primary function is to automate administrative tasks and provide a more efficient way to manage and control the server environment.nnTo locate PowerShell in Windows Server 2012, you can follow these steps:nn1. Click on the “Start” button or press the Windows key on your keyboard to open the Start Menu.nn2. In the Start Menu, locate the “Windows PowerShell” folder. It is usually found in the “Windows Administrative Tools” section. You can either scroll through the list or use the search bar to find it quickly.nn3. Click on the “Windows PowerShell” folder to expand it.nn4. Within the folder, you will find two options: “Windows PowerShell” and “Windows PowerShell ISE” (Integrated Scripting Environment). The former represents the standard PowerShell command-line interface, while the latter offers an enhanced scripting environment with additional features like syntax highlighting and debugging.nn5. Choose the appropriate option depending on your needs. If you’re just starting with PowerShell, the standard command-line interface should suffice.nnBy following these steps, you will be able to locate and access PowerShell in Windows Server 2012, allowing you to leverage its powerful features for system administration and automation tasks.”}},{“@type”:”Question”,”name”:”How do I enable PowerShell script on server?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”To enable PowerShell script on a server, you need to follow these steps:nn1. Open PowerShell as an administrator: Right-click on the Start menu button and select “Windows PowerShell (Admin)” from the context menu.nn2. Check the Execution Policy: Run the command `Get-ExecutionPolicy` to see the current execution policy. By default, it is likely set to “Restricted,” which prevents the execution of PowerShell scripts.nn3. Change the Execution Policy: To allow script execution, run the command `Set-ExecutionPolicy RemoteSigned`. This execution policy only allows the execution of scripts signed by trusted publishers. However, it allows the execution of local scripts without requiring a digital signature.nn4. Confirm the execution policy change: After setting the execution policy, run `Get-ExecutionPolicy` again to verify that it shows “RemoteSigned.”nn5. Run PowerShell scripts: Now, you can run PowerShell scripts on the server. To execute a script, open PowerShell, navigate to the script’s location using the `cd` (change directory) command, and then run the script using its file name and extension (e.g., `.scriptName.ps1`).nnBy following these steps, you can enable the execution of PowerShell scripts on your server without any security or permission issues. However, always exercise caution when running scripts from untrusted sources or those you have not thoroughly reviewed.”}},{“@type”:”Question”,”name”:”Is PowerShell 5.0 is included with Windows Server 2012 R2?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”Yes, PowerShell 5.0 is included with Windows Server 2012 R2. It was released as part of the Windows Management Framework (WMF) 5.0 update, which included updates to PowerShell, Windows Management Instrumentation (WMI), and the Server Manager CIM Provider.nnHere are the steps to verify that PowerShell 5.0 is included with Windows Server 2012 R2:nn1. Open the Start menu or press the Windows key on your keyboard.n2. Type “PowerShell” in the search bar and open the “Windows PowerShell” or “Windows PowerShell ISE” application.n3. Once the PowerShell console or ISE opens, type the following command and press Enter:n “`n $PSVersionTable.PSVersionn “`n4. The output will display the version of PowerShell installed on your system. If it shows as 5.0 or higher, then PowerShell 5.0 is included with Windows Server 2012 R2.nnNote: PowerShell versions can also be checked from the “Programs and Features” section in the Control Panel of Windows Server 2012 R2. Look for “Windows Management Framework 5.0” or “Windows Management Framework 5.1″ under the installed programs list to verify the installed version of PowerShell.”}},{“@type”:”Question”,”name”:”What version of PowerShell is available for Windows 2012 R2?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”PowerShell is a powerful task automation and configuration management framework developed by Microsoft. When it comes to Windows Server 2012 R2, it includes a pre-installed version of PowerShell. Here’s the version information.nnWindows Server 2012 R2 comes with PowerShell version 4.0 by default. PowerShell 4.0 introduced several new features and enhancements over its predecessor, such as Desired State Configuration (DSC), enhanced debugging capabilities, and improved language support.nnTo verify the installed PowerShell version on Windows Server 2012 R2, you can follow these steps:nn1. Launch PowerShell: Click on the Start button or press the Windows key, type “PowerShell,” and click on “Windows PowerShell” from the search results.n2. Run the command: In the PowerShell window, type the following command and press Enter:n `$PSVersionTable.PSVersion`nnThis command will display the PowerShell version information, including the major version, minor version, build version, and revision.nnPlease note that while PowerShell version 4 is the default version on Windows Server 2012 R2, it is possible to upgrade PowerShell to a newer version manually if desired. However, this answer is based on the assumption that the server is running the default configuration without any additional updates or modifications.”}},{“@type”:”Question”,”name”:”How to run PowerShell script from cmd?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”To run a PowerShell script from the Command Prompt (cmd), you can follow these steps:nn1. Open the Command Prompt: Press the Windows key, type “Command Prompt,” and click on the application when it appears in the search results.nn2. Navigate to the directory containing the PowerShell script: Use the “cd” command to change the directory to where the script is located. For example, if the script is located in “C:Scripts,” type `cd C:Scripts` and press Enter.nn3. Run the PowerShell script: Once you’re in the correct directory, you can execute the PowerShell script by entering the following command:nn “`n powershell -File scriptname.ps1n “`nn Replace “scriptname.ps1″ with the actual name of your PowerShell script, including the file extension.nn4. Press Enter to run the command, and the PowerShell script will execute.nnBy following these steps, you’ll be able to run PowerShell scripts directly from the Command Prompt, allowing you to automate various tasks or perform specific operations easily.”}},{“@type”:”Question”,”name”:”How to open PowerShell ISE in Windows Server 2012 R2?”,”acceptedAnswer”:{“@type”:”Answer”,”text”:”To open PowerShell ISE (Integrated Scripting Environment) in Windows Server 2012 R2, you can follow these steps:nn1. Launch the Start Menu: Click on the Windows logo located in the bottom-left corner of your screen or press the Windows key on your keyboard.n2. Search for PowerShell ISE: Begin typing “PowerShell ISE” in the search bar. As you type, the search results will start appearing.n3. Open PowerShell ISE: Once you see “Windows PowerShell ISE” in the search results, click on it to open the application.nnAlternatively, you can also use the Run dialog box to open PowerShell ISE:nn1. Press the Windows key + R on your keyboard simultaneously. This will open the Run dialog box.n2. In the Run dialog box, type “powershell_ise” (without quotes) and press Enter or click on the OK button.nnBy following these steps, you should be able to open PowerShell ISE on Windows Server 2012 R2.”}}]}

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Bcm943228hmb driver windows 10
  • Где хранятся ненужные файлы на диске с windows 10
  • Windows исчисляемое или неисчисляемое в английском
  • Как установить значок языка на панели задач windows 11
  • Как назначить горячую клавишу в windows xp