0

我编写了一个快速脚本来查找一个用户列表 (TEMP.txt) 中的用户在另一个用户列表 (TEMP2.txt) 中的百分比。它工作了一段时间,直到我的用户列表超过了 100,000 个左右……太慢了。我想将其转换为运行空间以加快速度,但我失败得很惨。原来的脚本是:

$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 %"

抱歉,我还是 powershell 的新手。

4

2 回答 2

0

不知道这对你有多大帮助,我也是运行空间的新手,但这里有一些我在 Windows 窗体中使用的代码,它在单独的运行空间中异步运行,你可以操纵它来做你需要的事情:

$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()
于 2016-03-31T20:14:59.357 回答
0

除了运行空间的概念,下一个脚本可以运行得更快一些:

$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 %"
于 2016-03-31T20:41:13.777 回答