在PowerShell中使用foreach -parallel

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在PowerShell中使用foreach -parallel相关的知识,希望对你有一定的参考价值。

我编写了一个脚本来使用foreach语法获取脱机集群资源,它工作正常。但我需要为50个集群获取集群离线资源,我尝试了foreach -parallel并收到错误。

workflow Test-Workflow {
    Param ([string[]] $clusters)
    $clusters = Get-Content "C:	empClusters.txt"
    foreach -parallel ($cluster in $clusters) {
        $clu1 = Get-Cluster -Name $cluster
        $clustername = $clu1.Name
        echo $clustername
        $clu2 = Get-Cluster $clustername |
                Get-ClusterResource |
                where { $_.Name -and $_.state -eq "offline" }
        echo $clu2
    }
}
Test-Workflow

输出:

slchypervcl003
slchypervcl004
Get-ClusterResource : The input object cannot be bound to any parameters for
the command either because the command does not take pipeline input or the
input and its properties do not match any of the parameters that take pipeline
input.
At Test-Workflow:8 char:8
+ 
    + CategoryInfo          : InvalidArgument: (slchypervcl003:PSObject) [Get-ClusterResource], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.FailoverClusters.PowerShell.GetResourceCommand
    + PSComputerName        : [localhost]

Get-ClusterResource : The input object cannot be bound to any parameters for
the command either because the command does not take pipeline input or the
input and its properties do not match any of the parameters that take pipeline
input.
At Test-Workflow:8 char:8
+ 
    + CategoryInfo          : InvalidArgument: (slchypervcl004:PSObject) [Get-ClusterResource], ParameterBindingException
    + FullyQualifiedErrorId : InputObjectNotBound,Microsoft.FailoverClusters.PowerShell.GetResourceCommand
    + PSComputerName        : [localhost]
答案

Get-ClusterResource只能将集群节点对象或集群组对象作为管道输入,并将其传递给-InputObject参数。 Get-Cluster命令返回一个对象类型Microsoft.FailoverClusters.PowerShell.Cluster,而不是所需的Microsoft.FailoverClusters.PowerShell.ClusterResource或Microsoft.FailoverClusters.PowerShell.ClusterNode对象,用于管道输入到Get-ClusterResource。如果您将代码更改为不使用管道并仅将集群名称作为参数值,那么结果如何变化?

更改以下内容:

$clu2 = Get-Cluster $clustername | Get-ClusterResource | where { $_.Name - 
and $_.state -eq "offline"}

至:

$clu2 = Get-ClusterResource -Name $clustername | where { $_.Name - 
and $_.state -eq "offline"}

要么:

$clu2 = Get-ClusterResource -Cluster $clustername | where { $_.Name - 
and $_.state -eq "offline"}

以上是关于在PowerShell中使用foreach -parallel的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PowerShell 中退出 ForEach-Object

foreach循环上的PowerShell + =添加重复的实例

PowerShell/CLI:具有多个数组的“Foreach”循环

Powershell 级联 Foreach 以导出到 Csv

$Files 中的 PowerShell ForEach $file

Powershell foreach