我有一个包含数据的.csv文件,我正试图将这些数据解析为一个txt文件。
.csv文件的内容如下所示
Name,Tag,Description
ServerA,BOH,Scheduling
ServerB,FOH,PrintServer
ServerC,BOH,DC我正在编写一个脚本,从该.csv导入数据并写入txt文件。下面是我试图让输出看起来像什么。
ServerA:
nodename: ServerA
description: Scheduling
Tag: BOH
username: svc_act
osFamily: windows
ServerB:
nodename: ServerB
description: PrintServer
Tag: FOH
username: svc_act
osFamily: windows
ServerC:
nodename: ServerC
description: DC
Tag: BOH
username: svc_act
osFamily: windows为了得到这个结果,我在下面的代码中遗漏了一些东西,但无法解决。谢谢你的帮助
$servers = import-csv -path C:\Temp\Servers.csv -UseCulture | ft
$output = $Servers | ForEach {
foreach($server in $servers){
"{$Server.name}"
"nodename = {$Server.name}"
"description = {$Server.description}"
"tag = {$Server.tag}"
"username: svc_act"
"osFamily: windows"
}
}
$output | Out-File -FilePath C:\temp\Serverstagdesc.txt发布于 2022-10-12 10:14:43
您期望的输出类似于Yaml,因此我建议您使用一个专用的解析器:PowerShell-Yaml。
Install-Module powershell-yaml
$HashTable = [Ordered]@{}
import-csv -path C:\Temp\Servers.csv |ForEach-Object {
$HashTable[$_.Name] = [Ordered]@{
nodename = 'BOERPT01'
description = $_.Description
tag = $_.Tag
}
}
$HashTable |ConvertTo-YamlServer1:
nodename: BOERPT01
description: Scheduling
tag: BOH
Server2:
nodename: BOERPT01
description: PrintServer
tag: FOH
Server3:
nodename: BOERPT01
description: DC
tag: BOH发布于 2022-10-12 09:48:31
$input = @'
Name,Tag,Description
Server,BOH,Scheduling
Server2,FOH,PrintServer
Server3,BOH,DC
'@ |
ConvertFrom-Csv
$template = "Server{0}:`r`n`tnodename: {1}`r`n`tdescription: {2}`r`n`tTag: {3}`r`n"
$counter = 0;
$formatedItems = $input |
ForEach-Object {
$counter++;
return [String]::Format($template, $counter, $_.Name, $_.Description, $_.Tag)
}
$output = [String]::Join('', $formatedItems)
$output | Out-File -FilePath ...https://stackoverflow.com/questions/74039217
复制相似问题