使用powershell分割数据

问题描述 投票:0回答:2

我有一个很棒的小脚本,它返回了我当时需要的内容。但事情发生了变化,现在我需要添加到我的脚本中。我的 powershell 技能有限。我做了一些搜索,但没有找到解决方案。可能是因为我不知道如何提出一个能得到正确答案的问题。

我有一个看起来像这样的数组:

钥匙 数据
按键-A 姓名1;姓名2;姓名3
KEY-B
KEY-C 姓名1

但我真的需要它:

钥匙 数据
按键-A 姓名1
按键-A 姓名2
按键-A 姓名3
KEY-C 姓名1

我正在考虑 foreach 和文本分割,但我无法让我的大脑告诉我的手指如何开始。

我尝试阅读 foreach 和(文本)split,但我似乎在一些很可能非常简单的事情上遇到了作家的障碍。

根据要求提供我当前数据的代码。我没有添加这个,因为我认为它与解决方案无关。

$tempcontent = $webrequscontent.Content | ConvertFrom-Json


if($tempcontent.total -eq 0){
    $exportdata = #foreach ($obj in $tempcontent.issues) 
        [PSCustomObject]@{
            key = ""
            data = " "
            }
}

else {
    $exportdata = foreach ($obj in $tempcontent.issues) 
    {
        [PSCustomObject]@{
            key = $obj.key
            Data = (($obj.fields.customfield_16170 | Select-String -Pattern $pattern -AllMatches).Matches.value) -join ';'
            }
    }
}

# convert objects to csv
$exportData | Export-CSV "H:\list.csv" -Delimiter ';' -NoTypeInformation 

arrays powershell split
2个回答
0
投票

JSON(或结果对象)的示例会有所帮助,但我认为您需要的是:

$exportData = if ($tempcontent.total -eq 0) {
    [PSCustomObject]@{
        # unless you prefer using $null or have some specific need, like whitespaces
        # [string]::Empty should be better for... well, empty strings.
        key  = [string]::Empty
        data = [string]::Empty
    }
}
else {
    foreach ($obj in $tempcontent.issues) {
        $obj.data -split ';' | ForEach-Object {
            [PSCustomObject]@{
                key  = $obj.key
                Data = (($obj.fields.customfield_16170 | Select-String -Pattern $pattern -AllMatches).Matches.value) -join ';'
            } 
        }
    }
} 

0
投票

只要您的数据与 $ArrayData 的表格式相同,这个简单的 foreach 循环就可以工作。

# Create your Json Table Example
$ArrayData = @(
[pscustomobject]@{Key = 'KEY-A' ;Data = 'Name1;Name2;Name3'}
[pscustomobject]@{Key = 'KEY-B' ;Data = ''}
[pscustomobject]@{Key = 'KEY-C' ;Data = 'Name1'}
)

# Format new pscustomobject and output to host
Foreach ($Array in $ArrayData){
    foreach ($Item in ($Array.Data -split ";")){
        [pscustomobject]@{Key = $Array.Key  ;Data = $Item}
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.