启用功能在powershell控制台中有效,但不在脚本中

时间:2018-05-18 15:18:13

标签: powershell powershell-remoting

我有一个脚本应该根据提供的列表安装功能。 out很好,但命令总是无法安装,但它们在powershell控制台中工作。

$features_to_enable=New-Object 
System.Collections.Generic.List[System.Object]

# We only want to read the features that are enabled. 
Get-Content 'C:\features.txt' | Where-Object {$_ -match ".*Enabled"} | 
ForEach-Object {
  $features_to_enable.Add($_)
}

# Converted List to Array
$features_to_enable.ToArray()

forEach($feature in $features_to_enable) {
  #Enable-WindowsOptionalFeature -Online -FeatureName "$($feature)" -All -NoRestart
  dism /Online /Enable /FeatureName:"$($feature)" /All
}

使用enable windows optional feature方法我收到此错误:

Enable-WindowsOptionalFeature : Feature name NetFx4ServerFeatures                                                           
Enabled is unknown.
At C:\features.ps1:12 char:3
+   Enable-WindowsOptionalFeature -Online -FeatureName "$($feature)" -A ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Enable-WindowsOptionalFeature], COMException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.EnableWindowsOptionalFeatureCommand

在powershell脚本中使用dism:

Deployment Image Servicing and Management tool
Version: 10.0.16299.15

Image Version: 10.0.16299.125


Error: 87

The enable option is unknown. 
For more information, refer to the help by running DISM.exe /?.

The DISM log file can be found at C:\Windows\Logs\DISM\dism.log

2 个答案:

答案 0 :(得分:0)

dism版本中,我认为Windows 10正在您的计算机上运行,​​因此建议使用PowerShell。

$features = (Get-WindowsOptionalFeature -Online | ? state -eq 'enabled').FeatureName
foreach($feature in $features) {
     Enable-WindowsOptionalFeature -FeatureName $feature -Online -All -NoRestart
    }

测试后这对我有用。 :)

答案 1 :(得分:0)

问题最终是字符串$ feature实际上是“Enabled”,我无法看到它们在同一行。

最后,我通过这样做解决了这个问题:

$f = $feature.replace(' ' , '').replace('Enabled', '')
Enable-WindowsOptionalFeature -Online -FeatureName $f -All -NoRestart