简体   繁体   中英

Converting a powershell script to Runspace

I wrote a quick script to find the percentage of users in one user list (TEMP.txt) that are also in another user list (TEMP2.txt) It worked great for a while until my user lists got up above a couple 100,000 or so... its too slow. I want to convert it to runspace to speed it up, but I am failing miserably. The original script is:

$USERLIST1 = gc .\TEMP.txt
$i = 0

ForEach ($User in $USERLIST1){
If (gc .\TEMP2.txt |Select-String $User -quiet){
$i = $i + 1
}
}
$Count = gc .\TEMP2.txt | Measure-object -Line

$decimal = $i / $count.lines

$percent = $decimal * 100

Write-Host "$percent %"

Sorry I am still new at powershell.

Not sure how much this will help you, I am new with runspaces as well but here is some code I used with a Windows Form running things asynchronously in a separate runspace, you might be able to manipulate it to do what you need:

$Runspace = [Management.Automation.Runspaces.RunspaceFactory]::CreateRunspace($Host)

$Runspace.ApartmentState = 'STA'
$Runspace.ThreadOptions = 'ReuseThread'
$Runspace.Open()

#Add the Form object to the Runspace environment
$Runspace.SessionStateProxy.SetVariable('Form', $Form)

#Create a new PowerShell object (a Thread)
$PowerShellRunspace = [System.Management.Automation.PowerShell]::Create()

#Initializes the PowerShell object with the runspace
$PowerShellRunspace.Runspace = $Runspace

#Add the scriptblock which should run inside the runspace
$PowerShellRunspace.AddScript({
    [System.Windows.Forms.Application]::Run($Form)
})

#Open and run the runspace asynchronously
$AsyncResult = $PowerShellRunspace.BeginInvoke()

#End the pipeline of the PowerShell object
$PowerShellRunspace.EndInvoke($AsyncResult)

#Close the runspace
$Runspace.Close()

#Remove the PowerShell object and its resources
$PowerShellRunspace.Dispose()

Apart from runspace concept, next script could run a bit faster:

$USERLIST1 = gc .\TEMP.txt
$USERLIST2 = gc .\TEMP2.txt

$i = 0

ForEach ($User in $USERLIST1) {
    if ($USERLIST2.Contains($User)) {
        $i += 1
    }
}

$Count = $USERLIST2.Count

$decimal = $i / $count
$percent = $decimal * 100
Write-Host "$percent %"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM