将powershell脚本转换为Runspace

时间:2016-03-31 19:35:50

标签: performance powershell runspace

我写了一个快速脚本来查找一个用户列表中的用户百分比(TEMP.txt),这些用户列表也位于另一个用户列表中(TEMP2.txt)它的工作时间很长,直到我的用户列表高于一对10万左右......太慢了。我想将它转换为运行空间以加速它,但我失败了。原始脚本是:

$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的新人。

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

runspace 概念外,下一个脚本可以运行得更快:

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