我是PS的新手,我正在尝试制作一个PS脚本,可以将具有特定信息的段落重新排列成一个可以轻松转换为csv文件的表单。
IP地址:192.168.1.1
主机名:测试
域名:contoso.com
IP地址:192.168.1.2
主机名:Test2
域名:contoso.com
IP地址;主机名;域;
192.168.1.1;测试; contoso.com
192.168.1.2; Test2的; contoso.com
是否可以这样做,你能举一些例子吗?提前致谢!
答案 0 :(得分:1)
这是一个解决方案:
示例输入文件:
IP Address: 192.168.1.1
Host Name: Test
Domain: contoso.com
IP Address: 192.168.1.2
Host Name: Test2
Domain: contoso.com
<强>脚本强>
Clear-Host
#loads the input file and removes the blank lines
$raw = Get-Content "G:\input\rawinfo.txt" | Where-Object { $_ -ne "" }
#declare results array
$results = @()
#foreach line in the input file
$raw | % {
#split the line on ": "
$data = $_ -Split ": "
#switch on first cell of data
switch ($data[0]) {
#store ip address
"IP Address" { $ipaddress= $data[1] }
#store host name
"Host Name" { $hostname = $data[1] }
#store domain
"Domain" {
$domain = $data[1]
#since this is the last field for each item
#build object with all fields
$item = [PSCustomObject]@{
"IP Address" = $ipaddress;
"Host Name" = $hostname;
"Domain" = $domain;
}
#add object to results array
$results += $item
}
}
}
#output results array
$results
示例输出:
IP Address Host Name Domain
---------- --------- ------
192.168.1.1 Test contoso.com
192.168.1.2 Test2 contoso.com
然后,您可以将其发送到Export-Csv
:
$results | Export-Csv "host_info.csv" -Delimiter ";" -NoTypeInformation
答案 1 :(得分:0)
我将假设信息在文本文件中 首先,您需要使用 Import-CSV 导入文件,处理数据并将其导出为NewCSV.csv
这是一个代码示例:
Import-Csv C:\test.txt -Delimiter ":" -Header "Name", "Value" |export-csv c:\test.csv -NoTypeInformation
这应该创建一个如下所示的文件:
"Name","Value"
"IP Address","192.168.1.1"
"Host Name","Test"
"Domain","contoso.com"
"IP Address","192.168.1.2"
"Host Name","Test2"
"Domain","contoso.com"
您可以使用-Delimiter ";"
Import-Csv C:\test.txt -Delimiter ":" -Header "Name", "Value" |export-csv c:\test.csv -NoTypeInformation -Delimiter ";"