Advertisement
Yevrag35

Import-CsvAsync

May 11th, 2020
1,654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Function New-Runspace([string]$Name, [string]$Path, [hashtable]$SyncHash, [System.Collections.Generic.List[object]]$Jobs)
  2. {
  3.     $importScript = {
  4.         param ([string]$Name, [string]$Path)
  5.         $import.Add($Name, (Import-Csv -Path $Path))
  6.     }
  7.  
  8.     $runspace = [runspacefactory]::CreateRunspace()
  9.     $runspace.ApartmentState = "STA"
  10.     $runspace.ThreadOptions = "ReuseThread"
  11.     $runspace.Open()
  12.     $runspace.SessionStateProxy.SetVariable("import", $SyncHash)
  13.  
  14.     $ps = [powershell]::Create().AddScript($importScript).AddParameter("Name", $Name).AddParameter("Path", $Path)
  15.     $ps.Runspace = $runspace
  16.     $async = [pscustomobject]@{
  17.         PowerShell = $ps
  18.         Runspace = $ps.BeginInvoke()
  19.     }
  20.     $Jobs.Add($async) | Out-Null
  21. }
  22.  
  23. Function Import-CsvAsync
  24. {
  25.     [CmdletBinding()]
  26.     [OutputType([hashtable])]
  27.     param
  28.     (
  29.         [Parameter(Mandatory=$true, Position = 0)]
  30.         [string[]] $FilePath,
  31.  
  32.         [Parameter(Mandatory=$false)]
  33.         [ValidateRange(1, [int]::MaxValue)]
  34.         [int] $CheckIntervalInMS = 1000
  35.     )
  36.     $import = [hashtable]::Synchronized(@{})
  37.     $import.Errors = New-Object 'System.Collections.Generic.List[System.Management.Automation.ErrorRecord]'
  38.  
  39.     $jobsList = New-Object System.Collections.Generic.List[object] -ArgumentList $FilePath.Length
  40.     foreach ($file in $FilePath)
  41.     {
  42.         $fileInfo = Get-ChildItem -Path $file
  43.         $nsArgs = @{
  44.             Name = $fileInfo.BaseName
  45.             Path = $fileInfo.FullName
  46.             SyncHash = $import
  47.             Jobs = $jobsList
  48.         }
  49.         New-Runspace @nsArgs
  50.     }
  51.    
  52.     while ($jobsList.Count -gt 0)
  53.     {
  54.         for ($i = $jobsList.Count - 1; $i -ge 0; $i--)
  55.         {
  56.             $job = $jobsList[$i]
  57.             if ($job.Runspace.IsCompleted)
  58.             {
  59.                 $job.PowerShell.EndInvoke($job.Runspace) | Out-Null
  60.                 if ($job.PowerShell.HadErrors)
  61.                 {
  62.                     $import.Errors.AddRange($job.PowerShell.Streams.Error)
  63.                 }
  64.                 $job.PowerShell.Dispose()
  65.                 $jobsList.Remove($job) | Out-Null
  66.             }
  67.         }
  68.         Start-Sleep -Milliseconds $CheckIntervalInMS
  69.     }
  70.     $import
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement