【问题标题】:Powershell Array to csvPowershell数组到csv
【发布时间】:2021-06-19 05:31:57
【问题描述】:

我对 powershell 很陌生,我不知道如何将我的数组放入一个 csv 文件中,其中每个字符串都进入一个新行。下面是一些示例代码。

$ServerList = "E:\Coding Projects\Powershell\ServerNameList.txt"
$ServerNames = Get-content $ServerList
write-host $ServerNames
$OutputPath = "E:\Coding Projects\Powershell\Output.csv"

$Names = @() 
$Outcome = @()
foreach ($Server in $ServerNames){
    $Names += $Server 
    if ($Server -match "Joe"){
        $Outcome += "pass" 
       
    }else{
        $Outcome += "Fail" 
    }

}
$Names
$Outcome

$csv = New-object psobject -property @{ 
    'User' = $Names -join ',' 
    'Groups' = $Outcome -join ','
    }

write-host $csv

$csv | Select-Object -property User, Groups | Export-csv -path $OutputPath -NoTypeInformation

当我检查 csv 文件时,所有输出都出现在一行上,而不是在其特定列中向下迭代行。 任何帮助都会非常有用和感激

【问题讨论】:

    标签: arrays powershell csv export-csv


    【解决方案1】:

    现在您正在创建 2 个单独的字符串值数组 - 相反,您需要创建一个具有两个属性的对象数组:

    $ServerList = "E:\Coding Projects\Powershell\ServerNameList.txt"
    $ServerNames = Get-content $ServerList
    write-host $ServerNames
    $OutputPath = "E:\Coding Projects\Powershell\Output.csv"
    
    $serversWithOutcome = @()
    foreach ($Server in $ServerNames){
        $serversWithOutcome += [pscustomobject]@{
            User = $Server 
            Groups = $Server -match "Joe" 
        }
    }
    
    $serversWithOutcome | Export-csv -path $OutputPath -NoTypeInformation
    

    【讨论】:

    • 谢谢。这比我预期的要简单得多!
    • 可能的改进:$serversWithOutcome = foreach ... 并删除 $serversWithOutcome +=。当foreach 的输出分配给这样的变量时,PowerShell 会自动创建一个数组。在内部,PowerShell 使用比+= 更有效的方法,它重新创建数组以适应每个新项目的大小。
    • @zett42 绝对!我坚持使用 OP 在这里使用+= 是有原因的——“服务器”是我们以 10 秒或 100 秒为单位计算的东西,如果你在一个大环境中可能是 1000 秒——但这不是我们的那种东西以百万计 - 换句话说,这并不重要 :-)
    猜你喜欢
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 2021-10-10
    • 2020-07-03
    • 2019-03-28
    • 2017-03-10
    • 2013-10-25
    • 1970-01-01
    相关资源
    最近更新 更多