Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Function New-Runspace([string]$Name, [string]$Path, [hashtable]$SyncHash, [System.Collections.Generic.List[object]]$Jobs)
- {
- $importScript = {
- param ([string]$Name, [string]$Path)
- $import.Add($Name, (Import-Csv -Path $Path))
- }
- $runspace = [runspacefactory]::CreateRunspace()
- $runspace.ApartmentState = "STA"
- $runspace.ThreadOptions = "ReuseThread"
- $runspace.Open()
- $runspace.SessionStateProxy.SetVariable("import", $SyncHash)
- $ps = [powershell]::Create().AddScript($importScript).AddParameter("Name", $Name).AddParameter("Path", $Path)
- $ps.Runspace = $runspace
- $async = [pscustomobject]@{
- PowerShell = $ps
- Runspace = $ps.BeginInvoke()
- }
- $Jobs.Add($async) | Out-Null
- }
- Function Import-CsvAsync
- {
- [CmdletBinding()]
- [OutputType([hashtable])]
- param
- (
- [Parameter(Mandatory=$true, Position = 0)]
- [string[]] $FilePath,
- [Parameter(Mandatory=$false)]
- [ValidateRange(1, [int]::MaxValue)]
- [int] $CheckIntervalInMS = 1000
- )
- $import = [hashtable]::Synchronized(@{})
- $import.Errors = New-Object 'System.Collections.Generic.List[System.Management.Automation.ErrorRecord]'
- $jobsList = New-Object System.Collections.Generic.List[object] -ArgumentList $FilePath.Length
- foreach ($file in $FilePath)
- {
- $fileInfo = Get-ChildItem -Path $file
- $nsArgs = @{
- Name = $fileInfo.BaseName
- Path = $fileInfo.FullName
- SyncHash = $import
- Jobs = $jobsList
- }
- New-Runspace @nsArgs
- }
- while ($jobsList.Count -gt 0)
- {
- for ($i = $jobsList.Count - 1; $i -ge 0; $i--)
- {
- $job = $jobsList[$i]
- if ($job.Runspace.IsCompleted)
- {
- $job.PowerShell.EndInvoke($job.Runspace) | Out-Null
- if ($job.PowerShell.HadErrors)
- {
- $import.Errors.AddRange($job.PowerShell.Streams.Error)
- }
- $job.PowerShell.Dispose()
- $jobsList.Remove($job) | Out-Null
- }
- }
- Start-Sleep -Milliseconds $CheckIntervalInMS
- }
- $import
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement