协助将此脚本写入excel文件

时间:2014-02-28 14:44:06

标签: excel powershell

我有这个脚本,它读入一个计算机名列表,并在每个VM(IP,子网,网关,DNS服务器,MAC)上写出网络详细信息。它的工作原理是脚本写入我的PowerShell窗口。我正在尝试添加一些代码来将输出写入.csv文件。这是我的剧本:

    $inputFile = "C:\Powershell_Scripts\IP_Mac\servers.txt"
    $csvFile = "C:\Powershell_Scripts\IP_Mac\results.csv"

 $report = @()

 foreach($Computer in (gc -Path $inputFile)){
  if(Test-Connection -ComputerName $Computer -Count 1 -ea 0) {
   $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $Computer | ? {$_.IPEnabled}
   foreach ($Network in $Networks) {
    $IPAddress  = $Network.IpAddress[0]
    $SubnetMask  = $Network.IPSubnet[0]
    $DefaultGateway = $Network.DefaultIPGateway
    $DNSServers  = $Network.DNSServerSearchOrder
    $IsDHCPEnabled = $false
    If($network.DHCPEnabled) {
     $IsDHCPEnabled = $true
    }
    $MACAddress  = $Network.MACAddress
    $OutputObj  = New-Object -Type PSObject
    $OutputObj | Add-Member -MemberType NoteProperty -Name ComputerName -Value $Computer.ToUpper()
    $OutputObj | Add-Member -MemberType NoteProperty -Name IPAddress -Value $IPAddress
    $OutputObj | Add-Member -MemberType NoteProperty -Name SubnetMask -Value $SubnetMask
    $OutputObj | Add-Member -MemberType NoteProperty -Name Gateway -Value ($DefaultGateway -join “,”)
    $OutputObj | Add-Member -MemberType NoteProperty -Name IsDHCPEnabled -Value $IsDHCPEnabled
    $OutputObj | Add-Member -MemberType NoteProperty -Name DNSServers -Value $DNSServers
    $OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress -Value $MACAddress
    $OutputObj
   }
  }
 }
     Write-Output $report
#}  

#When writing out the data in $node, use the tags defined in $properties to write out to a .csv file
$report | Select-Object -Property $properties | Export-Csv -Path $csvFile -NoTypeInformation

当我写出报告时,这是我最后一行的内容。您可以提供有关如何将结果写入文件的任何帮助。非常感谢。

谢谢。

1 个答案:

答案 0 :(得分:0)

您没有向$ report数组中添加任何内容,请更改上一个$OutputObj

...
$OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress 
             -Value $MACAddress
$OutputObj
}
...

...
$OutputObj | Add-Member -MemberType NoteProperty -Name MACAddress 
             -Value $MACAddress
$report += ,$OutputObj
}
...

和最后一行

$report | Select-Object -Property $properties |
          Export-Csv -Path $csvFile -NoTypeInformation

$report | Export-Csv -Path $csvFile -NoTypeInformation

要捕获无法连接的机器的详细信息,可以将第8行更改为:

try{
    $Networks = Get-WmiObject Win32_NetworkAdapterConfiguration 
    -ComputerName $Computer | ? {$_.IPEnabled}
}
catch{
    Write-Output($Computer + "`t" + $_.Exception.Message ) | 
    Out-File "C:\Powershell_Scripts\IP_Mac\bad_computers.tsv"
}

您将获得一个包含计算机名称和错误消息的tsv文件。

相关问题