帮助写出这个脚本到excel文件

我有这个脚本读取计算机名列表,并写出每个虚拟机(IP,子网,网关,DNS服务器,MAC)的networking细节。 它的作品在脚本写出我的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 

当我写出报告时,这是我的最后一行。 任何帮助您可以提供关于如何将结果写入文件将不胜感激。

谢谢。

您不会向$ 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文件。