【问题标题】:How use "Where-Object" condition with '[PScustomobject]'?如何将“Where-Object”条件与“[PScustomobject]”一起使用?
【发布时间】:2018-01-11 12:32:21
【问题描述】:

我有一些代码:

$output = [PSCustomObject]@{
    Name       = $ws.UsedRange.Columns.Item(1).Value2
    Department = $ws.UsedRange.Columns.Item(3).Value2
}

$output | GM
TypeName: System.Management.Automation.PSCustomObject

Name        MemberType   Definition                                  
----        ----------   ----------                                  
Equals      Method       bool Equals(System.Object obj)              
GetHashCode Method       int GetHashCode()                           
GetType     Method       type GetType()                              
ToString    Method       string ToString()                           
Department  NoteProperty System.Object[,] Department=System.Object[,]
Name        NoteProperty System.Object[,] Name=System.Object[,]   

我需要对我的$output 进行排序和过滤,但我不能。什么都没发生。可能做错了什么。

PS> $输出 名称 部门 ---- ---------- {数字,1,2,3,4,5,6,7...} {销售、IT、会计、开发人员...}

还有我的情况:

PS> $输出 |排序对象部门 - 降序 | Where-Object {$_.Department -eq "Sales"} 名称 部门 ---- ---------- {数字,1,2,3,4,5,6,7...} {销售、IT、会计、开发人员...}

【问题讨论】:

  • 您创建了一个 PSCustomObject,其中包含两个字段 NameDepartment。这是你想做的吗?
  • 我有 2 个主要“列”(编号、部门)的 excel 文件。 ~ 660 行。我想在 [pscustomobject] 中提取这些行,并在使用 'sort' 和 'where' 条件之后,以便能够按部门过滤数据。
  • 您可能要考虑将 Excel 文件另存为 CSV 是否更合适,然后通过管道传输到 Import-CSV 处理它ForEach-Object

标签: powershell powershell-4.0


【解决方案1】:

您创建了具有 2 个属性的单个对象,每个属性都包含其关联列的所有值。由于 Sort-ObjectWhere-Object 按属性对对象列表进行排序和过滤,因此这些 cmdlet 无需在此处执行任何操作。

您真正想要做的是每行创建一个对象。

$output = foreach ($row in $ws.UsedRange.Rows) {
    [PSCustomObject]@{
        Name       = $row.Columns.Item(1).Value2
        Department = $row.Columns.Item(3).Value2
    }
}

未经测试,因为我手头没有 MS Office。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-10
    • 2018-04-16
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多