1

我对 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 文件时,所有输出都出现在一行上,而不是在其特定列中向下迭代行。任何帮助都会非常有用和感激

4

1 回答 1

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
于 2021-03-22T14:46:38.343 回答