arrays - Powershell数组到csv
问题描述
我对 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 文件时,所有输出都出现在一行上,而不是在其特定列中向下迭代行。任何帮助都会非常有用和感激
解决方案
现在,您正在创建 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
推荐阅读
- python - 比较两个面具以确定哪个面具比另一个更像矩形 -> 测量矩形
- linux - 使用 cmake 在 Ubuntu 18.04 上构建 Flutter 引擎的问题
- php - 在 WooCommerce 结帐中刷新有关运输或付款方式更改的迷你购物车
- java - java中的递归(包括数组)
- c++ - 使用 2D std::vector 对 SYCL 进行矩阵乘法
- javascript - 通过 ES6 导入在浏览器中使用 socket.io
- java - 使用 NavigationView 时出错/应用程序崩溃
- postgresql - TypeOrm Postgres 对 where 子句值区分大小写
- github - Github Actions - 任何运行步骤都没有这样的文件或目录
- java - Thymeleaf 返回 Java 异常消息而不是我的自定义错误消息。我怎样才能让它返回我想要的?