2016-01-19 13 views
0

Powershell绝对不是我的“强项”之一,但每隔一段时间我会尝试编写脚本来自动执行手动任务。无论如何,这是我的问题。该脚本与WORKS一样,将导出一个csv文件并通过Hostname标头进行排序。我的问题是在那里有一个更好的方式来做到这一点?我的Powershell循环覆盖了以前的excel条目。使用Export-CSV -append重复条目

#Clear the output screen 
cls 

#set the working directory to where the script and text files are located (must be same directory) 
$scriptdir = Split-Path -Parent $PSCommandPath 
cd $scriptdir 

#set fileNamePaths for Export-Csv No Sort and Sorted to excel 
$FilePathNS = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll_NoSort.csv" 
$FilePathSort = "D:\PowerShell_Scripts\HP_Inventory\OAInfoAll.csv" 

#set up the ip subnet import 
$path = ".\EnclosureSubnets.txt" 
$ip = Get-Content $path 

#Loop to find OA information 
foreach ($subnet in $ip) { 

    $OAS = Find-HPOA $subnet -Timeout 250 -Verbose 
    $OAS | where {$_.Role -eq "Active"} | Export-Csv -NoTypeInformation -Append $FilePathNS 
} 

#Sort AOInfoAll.csv by hostname 
Import-Csv $FilePathNS | Sort-Object Hostname | Export-Csv $FilePathSort -NoTypeInformation 

如果我拿出追加然后循环将覆盖以前的条目,我只会用2个IP和2个主机名结束。当我再次运行脚本时追加修复此问题我得到重复/重复条目。

此外,我已经尝试在循环内使用排序对象主机名,但它只在排序每个单独的条目,因为它们被写入。这里是(IP和主机名是由)的例子:

IP     Hostname 
192.168.1.10  chassis03 
192.168.1.12  chassis05 
192.168.2.16  chassis01 
192.168.2.18  chassis02 
192.168.3.14  chassis07 
192.168.3.16  chassis08 

因此,尽管我的脚本工作,我想提前从“职业玩家”感谢一些反馈!

回答

0

不要在循环内导出,而是捕获所有捕获所有OAS的变量,并在输出为CSV之前对其进行排序。

foreach ($subnet in $ip) { 

    [array]$OAS += Find-HPOA $subnet -Timeout 250 -Verbose 

} 

$OAS | Where{$_.Role -eq 'Active'} | Sort Hostname | Export-Csv $FilePathSort -NoTypeInformation 

这会显着减少磁盘读取/写入的次数。