diff --git a/PoshRSJob/Public/Get-RSJob.ps1 b/PoshRSJob/Public/Get-RSJob.ps1 index 24b6ecb..286bf93 100644 --- a/PoshRSJob/Public/Get-RSJob.ps1 +++ b/PoshRSJob/Public/Get-RSJob.ps1 @@ -102,7 +102,7 @@ Function Get-RSJob { $DebugPreference = 'Continue' } Write-Debug "ParameterSet: $($PSCmdlet.parametersetname)" - $Hash = @{} + $SearchProps = New-Object System.Collections.ArrayList $ResultJobs = New-Object System.Collections.ArrayList } Process { @@ -112,14 +112,12 @@ Function Get-RSJob { if ($PSCmdlet.ParameterSetName -eq 'Job') { Write-Verbose "Adding Job $($PSBoundParameters[$Property].Id)" foreach ($v in $PSBoundParameters[$Property]) { - $Hash.Add($v.ID,1) + [void]$SearchProps.Add($v.ID) } } elseif ($PSCmdlet.ParameterSetName -ne 'All') { Write-Verbose "Adding $($PSBoundParameters[$Property])" - foreach ($v in $PSBoundParameters[$Property]) { - $Hash.Add($v,1) - } + $SearchProps.AddRange($PSBoundParameters[$Property]) } } End { @@ -127,27 +125,37 @@ Function Get-RSJob { if ($Property -eq 'Job') { $Property = 'ID' } $States = if ($PSBoundParameters.ContainsKey('State')) { '^' + ($State -join '$|^') + '$' } else { '.' } + [System.Threading.Monitor]::Enter($PoshRS_jobs.syncroot) + try { # IF faster than any scriptblocks - if ($PSCmdlet.ParameterSetName -eq 'All') { - Write-Verbose 'All Jobs' - $ResultJobs = $PoshRS_Jobs - } - else { - Write-Verbose "Filtered Jobs by $Property" - foreach ($job in $PoshRS_Jobs) { - if ($Hash.ContainsKey($job.$Property)) + if ($Property -eq 'All') { + Write-Verbose "Get all Jobs" + $ResultJobs = $PoshRS_Jobs + } + else { + Write-Verbose "Jobs by $Property" + # And Hash much faster than foreach{ foreach {} } inner loop + $Hash = @{} + foreach ($jobobj in $PoshRS_Jobs) { + $Hash[$jobobj.$Property] = $jobobj + } + foreach ($prop in $SearchProps) { + if ($Hash.Contains($prop)) { + [void]$ResultJobs.Add($Hash[$prop]) + } + } + } + foreach ($job in $ResultJobs) { + if (($job.State -match $States) -and + (-not $PSBoundParameters.ContainsKey('HasMoreData') -or $job.HasMoreData -eq $HasMoreData) + ) { - [void]$ResultJobs.Add($job) + $job } } } - foreach ($job in $ResultJobs) { - if (($job.State -match $States) -and - (-not $PSBoundParameters.ContainsKey('HasMoreData') -or $job.HasMoreData -eq $HasMoreData) - ) - { - $job - } + finally { + [System.Threading.Monitor]::Exit($PoshRS_jobs.syncroot) } } }