使用Powershell导入CSV时尝试匹配字符串

时间:2015-08-21 22:42:31

标签: powershell csv

我正在尝试创建一个报告,显示CSV文件中的旧操作系统。该程序精美地显示输出,但实际上并不解析任何东西。我试图将Windows 2000,2003,XP和Windows NT机器分开。样本数据如下:

Finding Title,IP Address / FQDN,Port,Service,OS,FQDN,Default Username,Default Password,Remediation Notes,Misc Notes,Misc Notes 2,Contact,Remediation
Default Password (yada) for 'yadayada' Account on Windows,fakefake,445,cifs,Microsoft Windows Server 2003 Service Pack 2,fakefake,yadayada,yadayada,Change the password.,,,,
Default Password (yadayada) for 'yadayada' Account on Windows,fakefake1,445,cifs,Microsoft Windows Server 2003 Service Pack 2,fakefake1,yadayada,yadayada,Change the password.,,,,
Default Password (yadayada) for 'yadayada' Account on Windows,fakefake2,445,cifs,Microsoft Windows Server 2003 Service Pack 1,fakefake2,yadayada,yadayada,Change the password.,,,,
Default Password (yadayada) for 'yadayada' Account on Windows,fakefake3,445,cifs,Microsoft Windows Server 2008 R2 Standard,fakefake3,yadayada,yadayada,Change the password.

到目前为止我的节目在这里:

$name = Read-Host 'CSV File?'
$csvs = import-csv $name
$object = $csvs.os


ForEach ( $object in $csvs ) {

if ($object -like '*2003*') { out-file  -inputobject $object  -append $name}
elseif ($object -like '*2000*') { out-file  -inputobject $object  -append $name}
elseif ($objects -clike '*NT*') { out-file  -inputobject $object  -append $name}
elseif ($object -clike '*XP*') { out-file  -inputobject $object  -append $name}
write-output $outfile
}
$a = "<style>"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:thistle}"
$a = $a + "TD{border-width: 1px;padding: 2px;border-style: solid;border-color: black;background-color:white}"
$a = $a + "TD:Nth-Child(Odd) {Background-Color: #dddddd;}"
$a = $a + "</style>"


import-csv $name | ConvertTo-HTML -head $a| Out-File C:\Users\myuser\Downloads\scripts\Test.htm

1 个答案:

答案 0 :(得分:0)

我认为你有一个错误,你有两个名为object的变量用于不同的目的:

$object = $csvs.os

ForEach ( $object in $csvs ) # object above getting overwritten

我会摆脱第一个对象赋值并按如下方式编写循环:

ForEach ( $object in $csvs ) {

if ($object.os -like '*2003*') { out-file  -inputobject $object  -append $name}
elseif ($object.os -like '*2000*') { out-file  -inputobject $object  -append $name}
elseif ($object.os -clike '*NT*') { out-file  -inputobject $object  -append $name}
elseif ($object.os -clike '*XP*') { out-file  -inputobject $object  -append $name}
}

虽然你可以避免这样的重复:

$csvs | where-object{ $_.os -like '*2003*' -or $_.os -like '*2000*' -or $_.os -clike '*NT*' -or $_.os -clike '*XP*'} |  out-file -append $name