如何在 Windows 10 上向 Get-WindowsOptionalFeature 返回真/假

Adr*_*ete 0 powershell windows-10

我试图在安装之前检查是否安装了 Windows 功能,以避免重新安装。

我用它来检查:

function Check-WindowsFeature {
    [CmdletBinding()]
    param(
        [Parameter(Position=0,Mandatory=$true)] [string]$FeatureName 
    )  
  if((Get-WindowsOptionalFeature -FeatureName $FeatureName -Online) -Like "Enabled") {
        # $FeatureName is Installed
        # (simplified function to paste here)
    } else {
        # Install $FeatureName 
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但是“if”总是返回false,即使安装了功能。
例子:

C:\> (Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online) -Like "Enabled"
False

C:\> Get-WindowsOptionalFeature -FeatureName Microsoft-Hyper-V-All -Online | ft -Property State
State
-----
Enabled
Run Code Online (Sandbox Code Playgroud)

我已经尝试过格式为表格,格式为宽,过滤器-Property State,输出为字符串,与正则表达式匹配,-eqcontains和匹配,但都不起作用。

功能$FeatureName正常,因为安装有效。

如何使这项工作?

Mar*_*ndl 5

这是因为Get-WindowsOptionalFeature的返回值是一个AdvancedFeatureObject. 您不能-Like在该对象上使用带有字符串的 。

相反,您必须访问该State对象上的属性并进行比较:

function Check-WindowsFeature {
    [CmdletBinding()]
    param(
        [Parameter(Position=0,Mandatory=$true)] [string]$FeatureName 
    )  
  if((Get-WindowsOptionalFeature -FeatureName $FeatureName -Online).State -eq "Enabled") {
        # $FeatureName is Installed
        # (simplified function to paste here)
    } else {
        # Install $FeatureName 
    }
  }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我会将函数的名称更改为类似的名称,Install-WindowsFeatureIfNotInstalled因为我不希望带有Check动词的函数在我的机器上安装任何东西