Как включить функцию Windows через Powershell
Мне нужно включить две функции Windows с помощью Powershell. Но я не знаю их имен или как их найти.
![Windows Features]()
До сих пор мне удалось установить IIS и остановить пул приложений по умолчанию с помощью script найденного здесь.
function InstallFeature($name) {
cmd /c "ocsetup $name /passive"
}
InstallFeature IIS-WebServerRole
InstallFeature IIS-WebServer
InstallFeature IIS-CommonHttpFeatures
InstallFeature IIS-DefaultDocument
InstallFeature IIS-DirectoryBrowsing
InstallFeature IIS-HttpErrors
InstallFeature IIS-HttpRedirect
InstallFeature IIS-StaticContent
InstallFeature IIS-HealthAndDiagnostics
InstallFeature IIS-CustomLogging
InstallFeature IIS-HttpLogging
InstallFeature IIS-HttpTracing
InstallFeature IIS-LoggingLibraries
InstallFeature IIS-Security
InstallFeature IIS-RequestFiltering
InstallFeature IIS-WindowsAuthentication
InstallFeature IIS-ApplicationDevelopment
InstallFeature IIS-NetFxExtensibility
InstallFeature IIS-ISAPIExtensions
InstallFeature IIS-ISAPIFilter
InstallFeature IIS-ASPNET
InstallFeature IIS-WebServerManagementTools
InstallFeature IIS-ManagementConsole
InstallFeature IIS-ManagementScriptingTools
import-module WebAdministration
Stop-WebAppPool DefaultAppPool
Решение
Для поиска:
Get-WindowsFeature *ASP*
Get-WindowsFeature *activation*
Для установки:
Add-WindowsFeature NET-Framework-45-ASPNET
Add-WindowsFeature NET-HTTP-Activation
Ответы
Ответ 1
если вы находитесь в Windows 2008R2, для этого есть модуль:
Import-Module servermanager
этот модуль экспортирует 3 командлета: Get-WindowsFeature
, Add-WindowsFeature
и remove-WindowsFeature
чтобы вы могли
get-windowsfeature *frame*
, чтобы перечислить функции .net и установить его с помощью команды, например
Add-WindowsFeature Net-Framework
Ответ 2
Для более новой клиентской ОС Windows (Windows 10/8.1/8) вы не можете использовать Install-WindowsFeature, поскольку это только для управления функциями на серверах. Попытка использовать его вызовет сообщение об ошибке:
Get-WindowsFeature: Цель указанного командлета не может быть операционной системой на базе Windows.
Существует модуль DISM Powershell, который вы можете использовать для поиска и установки дополнительных функций:
gcm -module DISM #List available commands
Get-WindowsOptionalFeature -online | ft #List all features and status
Enable-WindowsOptionalFeature -online -FeatureName NetFx3 -Source e:\Sources\sxs
В последней команде -Source e:\Sources\sxs
требуется только в том случае, если функция должна ссылаться на установочный носитель для исходных файлов (обычно для исправления ошибки: 0x800f081f Исходные файлы не найдены). Версия .NET Framework 3.5 кажется единственной, которая требует, чтобы для клиентской ОС, но в ОС сервера есть много других, которые требуют ссылки на установочный носитель для источников.
Ответ 3
Попробуйте это, чтобы получить имена (короткие) и отображаемые имена (длинные описания):
get-windowsfeature | format-table -property name, displayname -AutoSize
используйте это, чтобы установить их:
Install-WindowsFeature -Name $Name
где $Name - это свойство имени из get
PS: Install-WindowsFeature заменил Add-WindowsFeature
Ответ 4
Самый простой способ (он работал у меня):
- возьмите компьютер, на котором не установлены необходимые роли и функции.
- перейдите к разделу Добавление ролей сервера и его функций (в диспетчере серверов)
- используйте мастер, чтобы добавить необходимые роли и функции.
- на последнем экране перед нажатием кнопки "Установить" вы увидите ссылку "Экспорт настроек конфигурации"
Экспорт настроек конфигурации
Сохраните файл XML.
После того, как у вас есть файл XML, вы можете использовать PowerShell script, перечисленные ниже, для вызова командлета "Install-WindowsFeature" (Server 2012, 2016).
ПРИМЕЧАНИЕ 1: PowerShell script был разработан для работы в Windows Server 2008, 2012 и 2016.
Для Windows Server 2008 командлет - Add-WindowsFeature.
ПРИМЕЧАНИЕ 2. PowerShell script предполагает, что файл XML находится в одной и той же папке, и это имя указано внутри script - см. строки 3 и 4.
Import-Module ServerManager -ErrorAction Stop
$win2k8xml = '.\features-w2k8.xml'
$win2k12xml = '.\RolesAndFeatures.xml'
$minOSVersion = [version] "6.1.7600" # Windows Server 2008 R2 RTM version
$os = Get-WmiObject Win32_OperatingSystem
$currentVersion = [version]$os.Version
if($currentVersion -lt $minOSVersion)
{
throw "OS version equal or greater than ${minOSVersion} is required to run this script"
}
elseif($currentVersion.ToString().substring(0,3) -eq $minOSVersion.ToString().substring(0,3))
{
If (!(Test-Path $win2k8xml)) {Write-Host "For Windows Server 2008 R2 server make sure that you have Features-W2K8.xml in the current folder" -ForegroundColor Yellow; Pause}
}
elseif($currentVersion -gt $minOSVersion){
If (!(Test-Path $win2k12xml)) {Write-Host "For Windows Server 2012/2016 make sure that you have RolesAndFeatures.xml in the current folder" -ForegroundColor Yellow; Pause}
}
$OSVersionName = (get-itemproperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" -Name ProductName).ProductName
Write-Host "Your OS version is:$OSVersionName" -ForegroundColor Green
$defaultComputerName = $env:computername
$ComputerName = Read-Host "Computername (Press Enter for current computer - $defaultComputerName)"
if ([string]::IsNullOrEmpty($ComputerName))
{
$ComputerName = $defaultComputerName;
}
Write-host "Installation will take place on the following computers: $ComputerName"
function Invoke-WindowsFeatureBatchDeployment {
param (
[parameter(mandatory)]
[string] $ComputerName,
[parameter(mandatory)]
[string] $ConfigurationFilePath
)
# Deploy the features on multiple computers simultaneously.
$jobs = @()
if(Test-Connection -ComputerName $ComputerName -Quiet){
Write-Host "Connection succeeded to: " $ComputerName
if ($currentVersion.ToString().substring(0,3) -eq $minOSVersion.ToString().substring(0,3)) {
$jobs += Start-Job -Command {
#Add-WindowsFeature -ConfigurationFilePath $using:ConfigurationFilePath -ComputerName $using:ComputerName -Restart
$import = Import-Clixml $using:ConfigurationFilePath
$import | Add-WindowsFeature
}
}
elseif ($currentVersion -gt $minOSVersion) {
$jobs += Start-Job -Command {
Install-WindowsFeature -ConfigurationFilePath $using:ConfigurationFilePath -ComputerName $using:ComputerName -Restart
}
}
}
else{
Write-Host "Configuration failed for: "+ $ComputerName + "! Check computer name and execute again"
}
Receive-Job -Job $jobs -Wait | Select-Object Success, RestartNeeded, ExitCode, FeatureResult
}
if ($currentVersion.ToString().substring(0,3) -eq $minOSVersion.ToString().substring(0,3)) {$FilePath = Resolve-Path $win2k8xml}
elseif ($currentVersion -gt $minOSVersion) {$FilePath = Resolve-Path $win2k12xml}
Invoke-WindowsFeatureBatchDeployment $ComputerName $FilePath