2015-06-03 63 views
0

必須有一種更高效的方法,可以將文件名稱包含Services_Results * .csv的目錄中的多個CSV文件導入具有唯一條目的一個變量。我正在考慮通過與通配符匹配文件名的目錄中的所有文件循環,然後只導入字段中成功的行。從目錄導入多個CSV文件的更有效方式

$Success0 = Import-Csv -Path "\\FILE05\Users\USER001\+Projects\Chrome\Services_Results.csv" | Where-Object {$_.Status -eq "Success"} 
$Success1 = Import-Csv -Path "\\FILE05\Users\USER001\+Projects\Chrome\Services_Results_150601.csv" | Where-Object {$_.Status -eq "Success"} 
$Success2 = Import-Csv -Path "\\FILE05\Users\USER001\+Projects\Chrome\Services_Results_150602.csv" | Where-Object {$_.Status -eq "Success"} 
$Success3 = Import-Csv -Path "\\FILE05\Users\USER001\+Projects\Chrome\Services_Results_150602_b.csv" | Where-Object {$_.Status -eq "Success"} 
$Success4 = Import-Csv -Path "\\FILE05\Users\USER001\+Projects\Chrome\Services_Results_150602_c.csv" | Where-Object {$_.Status -eq "Success"} 
$Success5 = Import-Csv -Path "\\FILE05\Users\USER001\+Projects\Chrome\Services_Results_150603_a.csv" | Where-Object {$_.Status -eq "Success"} 

$PCList = $Success0 + $Success1 + $Success2 + $Success3 + $Success4 + $Success5 
$PCList = $PCList.PC | sort -Unique 
Write-host "PCList" $PCList.count 
+0

$ PCList.PC是字段包含PC名稱。當有多個數據列時,我無法弄清楚如何創建唯一條目列表。 –

回答

1

從獲取幫助進口CSV:

-Path <String[]> 
    Specifies the path to the CSV file to import. You can also pipe a path to Import-Csv. 

    Required?     false 
    Position?     1 
    Default value    None 
    Accept pipeline input?  true (ByValue) 
    Accept wildcard characters? false 

所以進口CSV會從管道接受多個值的路徑:

$PCList = 
Get-ChildItem '\\FILE05\Users\USER001\+Projects\Chrome\Services_Results*.csv' | 
Select -ExpandProperty FullName | 
Import-CSV | 
Where-Object {$_.Status -eq "Success"} 
0

如何使用PowerShell後臺作業加快這個過程?我沒有測試過這個代碼,但是嘗試閱讀了解這個模式。如果您要導入大量的CSV文件,我認爲您會理解它可以加快進程的速度。

### Create an empty array to hold Background Jobs. 
$JobList = @(); 

### Get a list of CSV files. 
$FileList = Get-ChildItem -Path \\FILE05\Users\USER001\+Projects\Chrome\*Services_Results*.csv; 

foreach ($File in $FileList) { 
    ### Start a new Background Job for each file 
    $JobList += Start-Job -ScriptBlock { Import-Csv -Path $args[0] | Where-Object -FilterScript { $PSItem.Status -eq 'Success'; } } -ArgumentList $File.FullName -Name $File.Name; 
} 

### Wait for all the jobs to complete. 
Wait-Job -Job $JobList; 

### Receive the results of the jobs. 
$ResultList = Receive-Job -Job $JobList; 
0

我認爲你可以做你想做很整齊地與你已經在做了,但使用通配符和foreach循環中的方式是什麼:

$files = Get-ChildItem "\\FILE05\Users\USER001\+Projects\Chrome\*.csv" 
$PCList = $files | ForEach { (Import-Csv $_ | Where Status -eq "Success") } 

$PCList = $PCList | sort -Unique -Property PC 
Write-Output $PCList 
Write-Output $PCList.Count 
相關問題