powershell - 在Powershell中拆分属性值

标签 powershell

我目前正在尝试使用Out-GridView来获得有关我们的组策略对象的简单概述。为此,我正在使用Get-GPO cmdlet,如下所示:

Get-GPO -all |
    Select-Object -Property DisplayName, Description |
    Sort-Object -Property DisplayName |
    Out-GridView

在我们公司中,我们使用description字段的第一行来存储创建策略的管理员的姓名,随后的所有行都包含简短的描述。

我希望能够使用列标题Description和其他字段在单独的列中捕获Responsability字段的第一行。因此,假设我当前的代码会给我一个像这样的表:
DisplayName | Description
-------------------------
GPO1        | Username
            | stuff
            | stuff

我希望它看起来像这样:
DisplayName | Responsability | Description
------------------------------------------
GPO1        | Username       | stuff
            |                | stuff

我该如何实现?

最佳答案

如@Matt建议,您可以使用calculated property

然后,由于Description是一个字符串,而不是一个字符串数组,因此您需要在换行符处拆分该行。这可以通过使用-split来完成,并且由于它是来自GPO的信息,因此我们可以假定Windows行尾为`r`n(否则可以使用[environment]::newline)

第一个属性,使用数组元素[0]将是第一行。对于第二个属性,我们需要将数组保存在变量中。然后,我们可以使用该变量的长度来获取第一个元素到最后一个元素。

Get-GPO -all |
    Select-Object -Property DisplayName, @{
            Name = "Responsibility"
            Expression = {($_.Description -split "`r`n")[0]}
        }, @{
            Name = "Description"
            Expression = {
                $linearray = ($_.Description -split "`r`n")
                $linearray[1..($linearray.length - 1)] | Out-String
            }
        } |
    Sort-Object -Property DisplayName |
    Out-GridView

或者,您可以创建一个新对象,而不使用计算所得的属性。
Get-GPO -all |
    ForEach-Object {
        $linearray = ($_.Description -split "`r`n")
        [pscustomobject]@{
            "DisplayName" = $_.DisplayName
            "Responsibility"= $linearray[0]
            "Description" = $linearray[1..($linearray.length - 1)] | Out-String
        }
    } |
    Sort-Object -Property DisplayName |
    Out-GridView

关于powershell - 在Powershell中拆分属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44530016/

相关文章:

excel - Powershell 的 .csv 文件输出显示在 Excel 的一列中

azure - 如何通过 powershell 脚本更新智能检测设置警报

powershell - 使用网络打印机添加打印机失败

powershell - 如何在Powershell上重用/扩展功能?

powershell - 重命名失败,因为它代表路径或设备名称

powershell - Pester Testdrive不存在

powershell - 根据字段条件过滤 PSCustomObject 值

powershell - PowerShell 的 setlocal/endlocal 等效项是什么?

xml - 使用 powershell 将文件夹结构转换为 XML 文件

powershell - 选项 -recurse 有时不适用于 PowerShell cmdlet get-childitem