从powershell创建CSV文件,列出现空单元格问题

ifmq2ha2  于 2023-06-03  发布在  Shell
关注(0)|答案(1)|浏览(234)

我的问题是,我需要创建CSV文件,将打印值在单独的列,旁边的对方。现在我有单独的列,但有空单元格。
例如:列B具有从单元格1开始直到单元格8的值。列C将从单元格9开始打印值,但应该从单元格1开始。它包含B列值下的值,但我需要它们彼此相邻。
我有这样的代码

$allsites = @(
'newone'
'new'
'one'
)

# Set the path to save the CSV file
$csvFilePath = "C:\PATH"

$parameters = @(

)

# Create an empty array to store the parameter values
# $parameters = @()

foreach ($site in $allsites) {

    $xmlFilePath = "C:\PATH"
    $xmlContent = [xml](Get-Content -Path $xmlFilePath)

    $allparameters = @(

        'parameter1'
        'Parameter2'
        'Parameter3'
        'Parameter4'

    )


    foreach ($parameter in $allparameters) {
        $parameterNode = $xmlContent.SelectSingleNode("//add[@key='$parameter']")
        if ($parameterNode -eq $null) {
            $parameterValue = "Parameter not found or commented out."
        } else {
            $parameterValue = $parameterNode.getAttribute("value")
        }

        Write-Host $parameterValue

        $paramObj = [PSCustomObject]@{
            A = ''
            B = ''
            C = ''
            D = ''
        }

        if ($site -eq "newone") {
            $paramObj.B = $parameterValue
        }
        elseif ($site -eq "new") {
            $paramObj.C = $parameterValue
        }
        elseif ($site -eq "one") {
            $paramObj.D = $parameterValue
        }

        $parameters += $paramObj
    }



    # Export the parameter values to the CSV file
    if ($parameters.Count -gt 0) {
        $parameters | ConvertTo-Csv -NoTypeInformation | Select-Object -Skip 1 | Out-File -FilePath $csvFilePath -Encoding UTF8 -Append
        # Clear the $parameters array for the next iteration
        
        $parameters = @()
    }

    timeout /t 20
}

Write-Host "CSV file created successfully at $csvFilePath"

timeout /t 10

下面是一段输出

"A","B","C","D"
"","JIRA","",""
"","false","",""
"","1200","",""
"","0","",""
"","true","",""
"","Parameter not found or commented out.","",""
"A","B","C","D"
"","","JIRA",""
"","","false",""
"","","1200",""
"","","0",""
"","","yesyoucan",""
"","","Parameter not found or commented out.",""
"A","B","C","D"
"","","","JIRA"
"","","","false"
"","","","1200"
"","","","0"
"","","","dzialaj"
"","","","Parameter not found or commented out."

我需要的是
打印值在单独的列中彼此相邻,没有空单元格。每列应从单元格1开始。
你能帮忙吗?我找不到解决办法。我觉得应该是这条线的东西
为下一次迭代清除$parameters数组$parameters = @()它应该只包含A、B、C的参数,不包含任何空值。
我尝试了add-member,并尝试编写一些条件,以避免添加空值。

xienkqul

xienkqul1#

这是非常直接的修复-只需将默认属性值更改为空字符串而不是$null

$paramObj = [PSCustomObject]@{
    A = ''
    B = ''
    C = ''
    D = ''
}

相关问题