2016-01-19 12 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 

這會顯着減少磁盤讀取/寫入的次數。