首页 > 解决方案 > 如何将数据从 Powershell 导出到 Csv 文件中,并在其他列中包含现有数据的行?

问题描述

我要做的是根据需要在哪一列一次将数据添加到 Csv 文件中的一个单元格。我当前的脚本使用Add-Contentcmdlet,然后-Value ",,$data"根据逗号的数量将其插入到所需的列中。但是,该Add-Contentcmdlet 在每次调用时都会插入一个新行,因此我的数据看起来非常零散。

我能找到的唯一其他解决方案是创建一个临时对象以导出到 Csv(即New-Object PSObject -Property @{col1 = $data}),但这不会让我在标题行之后插入多于一行。

我当前的代码:

ForEach ($user in $subSite.Users) {
    if (($user -ne $null) -and ($user.Name -ne $null)) {
        if ($user.Roles.Name -contains "Full Control") {
            Add-Content -Path $outFile -Value ",$user"
        }
        elseif ($user.Roles.Name -contains "Site Owner") {
            Add-Content -Path $outFile -Value ",,$user"
        }
        elseif ($user.Roles.Name -contains "Site Administrator") {
            Add-Content -Path $outFile -Value ",,,$user"
        }
    }
}

所有帮助表示赞赏。谢谢!

编辑:这是写入输出文件的示例。并不是说它很重要,而是在脚本的前面添加了标题。

https://drive.google.com/file/d/1Sbye-ZU9PouOPwBOXdtke-xJooloaFRz/view?usp=sharing

请注意分段,因为Add-Content每次调用都会创建一个新行。我考虑了该-NoNewLine参数,但如果我需要将一条新数据添加到同一列,那将不起作用。

标签: powershell

解决方案


推荐阅读