在PowerShell中作为工作流运行时,Where-Object子句失败

时间:2014-04-01 12:37:08

标签: powershell workflow

我正在尝试使用Get-NetRoute cmdlet从所有AD计算机中提取静态路由。它在工作流程外运行时效果很好,但是一旦我尝试在工作流程中运行相同的代码,它就会失败并出现以下异常:

System.Management.Automation.ParameterBindingException: Parameter set cannot be resolved using the specified named parameters.

我可以追溯到Where-Object“?”过滤。注释的代码行中的“?{}”部分使其失败。没有那个过滤器,它可以很好地工作。

代码在这里:

cd C:\Users\Public\Documents

workflow Get-StaticRoutes  {
    # Change the error action to 'stop' to get try/catch working
    # Get-NetRoute -Protocol NetMgmt -AddressFamily IPv4 | ? { $_.DestinationPrefix -ne "0.0.0.0/0" } | % {
    Get-NetRoute -Protocol NetMgmt -AddressFamily IPv4 | % {
        [PSCustomObject] @{
            ComputerName      = $env:COMPUTERNAME
            InterfaceName     = $_.InterfaceAlias
            InterfaceIndex    = $_.InterfaceIndex
            DestinationPrefix = $_.DestinationPrefix
            NextHop           = $_.NextHop
            Comment           = ""
        }
    }
}

# Get all computers from AD
$computers = Get-ADComputer -Filter * | % { $_.Name }

# Retrieve IP config
Get-StaticRoutes -PSComputerName $computers | Export-Csv ".\StaticRoutes.csv" -NoTypeInformation

我可以在工作流程之后过滤来解决这个问题,但我想了解我做错了什么,因为这个ParameterBindingException相当模糊。

谢谢,

奥利弗。

2 个答案:

答案 0 :(得分:1)

要在工作流中运行在Windows PowerShell中有效但在工作流中无效的命令或表达式,请在inlineScript活动中运行命令。您还可以使用inlineScript活动在工作流中运行Windows PowerShell脚本(.ps1文件)。

试试这个(未经测试)

workflow Get-StaticRoutes  
{   
   inlinescript { Get-NetRoute -Protocol NetMgmt -AddressFamily IPv4 |
                     ? { $_.DestinationPrefix -ne "0.0.0.0/0" } | 
                % {
                    [PSCustomObject] @{
                                        ComputerName      = $env:COMPUTERNAME
                                        InterfaceName     = $_.InterfaceAlias
                                        InterfaceIndex    = $_.InterfaceIndex
                                        DestinationPrefix = $_.DestinationPrefix
                                        NextHop           = $_.NextHop
                                        Comment           = ""
                                       }
                   }
                }
}

旁注:

    inlinescipt活动之外的
  • $env:computername解析为本地 电脑名称。 inlinescipt活动内部解析到远程 电脑名称。

    • 工作流返回的对象是序列化对象,而不是inlinescript活动或工作流过程中创建的对象(这意味着,简单来说,您不能拥有对象方法,只能拥有对象的属性)< / LI>

答案 1 :(得分:1)

请记住,使用工作流程时,您需要使用命名参数。 当你运行这样的东西时:

$a = $b | ?{$_.Name -eq "John"}

你真的在运行这个:

$a = $b | where-object -FilterScript {$_.Name -eq "John"}

后者在工作流程中工作正常,而不使用那些讨厌的inlinescripts。