使用重复参数执行Get-Command

时间:2018-01-19 12:20:40

标签: powershell

以下powershell命令无法执行,因为Get-Command包含-Name参数两次:

Get-Command -Name "Get-Service" -Name "Spooler"

这有效:

Get-Command -Name "Get-Service" -DisplayName "Spooler"

有解决方法吗?我们的应用程序需要使用Get-Command来阻止PowerShell代码在验证之前被调用。

我们的应用程序处理我们自己不写的powershell代码,因此我们必须考虑每个可能的场景,用户可以输入-Name但也输入-DisplayName。

编辑:更多说明:

#this code works, we have no control over the part after fhe first -Name
#and any solution has to be dynamic
Get-Command -Name "Get-Service" -DisplayName "Spooler"

#this does not work due to the duplicate -Name parameter
Get-Command -Name "Get-Service" -Name "Spooler"

1 个答案:

答案 0 :(得分:0)

它只是概念证明,但您可以这样开发:

$ExecutionContext.InvokeCommand.PreCommandLookupAction = `
{ 
    param($commandName, $commandLookupEvent)

    if ($commandName -eq 'Get-Command')
    {
        $commandLookupEvent.CommandScriptBlock = `
        {
            $getCommandArgs = @{}

            for ($i = 0; $i -lt $args.Length; $i += 2)
            {
                $parameterName = $args[$i]
                $parameterValue = $args[$i + 1]

                if (-not $getCommandArgs.ContainsKey($parameterName))
                {
                    $getCommandArgs.$parameterName = New-Object Collections.ArrayList
                }

                $getCommandArgs.$parameterName.Add($parameterValue) | Out-Null
            }

            Microsoft.PowerShell.Core\Get-Command @getCommandArgs
        }
    }
}

Get-Command -Name "Get-Service" -Name "Get-Item"

输出:

CommandType     Name             Version    Source                                                                                                 
-----------     ----             -------    ------
Cmdlet          Get-Service      3.1.0.0    Microsoft.PowerShell.Management                                                                        
Cmdlet          Get-Item         3.1.0.0    Microsoft.PowerShell.Management