我有这段代码,它是基于时间范围返回SQL行列表的函数的一部分。
查询本身(第一行代码)相当快。但是提取相关数据的foreach循环需要一段时间才能完成。
我有大约350.000行要迭代,尽管需要一段时间,我想知道是否有任何改变,以使它更快。
$SqlDocmasterTableResuls = $this.SqlConnection.GetSqlData("SELECT DOCNUM, DOCLOC FROM MHGROUP.DOCMASTER WHERE ENTRYWHEN between '" + $this.FromDate + "' and '" + $this.ToDate + "'")
[System.Collections.ArrayList]$ListOfDocuments = [System.Collections.ArrayList]::New()
if ($SqlDocmasterTableResuls.Rows.Count)
{
foreach ($Row in $SqlDocmasterTableResuls.Rows)
{
$DocProperties = @{
"DOCNUM" = $Row.DOCNUM
"SOURCE" = $Row.DOCLOC
"DESTINATION" = $Row.DOCLOC -replace ([regex]::Escape($this.iManSourceFileServerName + ":" + $this.iManSourceFileServerPath.ROOTPATH)),
([regex]::Escape($this.iManDestinationFileServerName + ":" + $this.iManDestinationFileServerPath.ROOTPATH))
}
$DocObj = New-Object -TypeName PSObject -Property $DocProperties
$ListOfDocuments.Add($DocObj)
}
return $ListOfDocuments发布于 2018-10-07 23:16:39
避免追加到循环中的数组。捕获变量中循环数据的最佳方法是简单地收集变量中的循环输出:
$ListOfDocuments = foreach ($Row in $SqlDocmasterTableResuls.Rows) {
New-Object -Type PSObject -Property @{
"DOCNUM" = $Row.DOCNUM
"SOURCE" = $Row.DOCLOC
"DESTINATION" = $Row.DOCLOC -replace ...
}
}您不需要周围的if条件,因为如果表没有任何行,则循环应该跳过它,留下一个空的结果。
因为您无论如何都想返回列表,所以甚至不需要收集变量中的循环输出。只要保持输出的原样,它就会被返回。
此外,当循环中的结果不发生变化时,避免重复操作。在循环之前计算一次转义源和目标路径:
$srcPath = [regex]::Escape($this.iManSourceFileServerName + ':' + $this.iManSourceFileServerPath.ROOTPATH)
$dstPath = [regex]::Escape($this.iManDestinationFileServerName + ':' + $this.iManDestinationFileServerPath.ROOTPATH)并在循环中使用变量$srcPath和$dstPath。
像这样的事情应该可以做到:
$SqlDocmasterTableResuls = $this.SqlConnection.GetSqlData("SELECT ...")
$srcPath = [regex]::Escape($this.iManSourceFileServerName + ':' + $this.iManSourceFileServerPath.ROOTPATH)
$dstPath = [regex]::Escape($this.iManDestinationFileServerName + ':' + $this.iManDestinationFileServerPath.ROOTPATH)
foreach ($Row in $SqlDocmasterTableResuls.Rows) {
New-Object -Type PSObject -Property @{
'DOCNUM' = $Row.DOCNUM
'SOURCE' = $Row.DOCLOC
'DESTINATION' = $Row.DOCLOC -replace $srcPath, $dstPath
}
}
return发布于 2018-10-07 23:56:03
编辑-每一个Ansgar,PSCO加速器是唯一可用的ps3+.
另一件可能有帮助的事情是用[PSCustomObject]代替[PSCustomObject]。这通常使用起来要快一些。就像这样..。
$DocObj = [PSCustomObject]$DocProperties使用这种类型加速器的另一种方法是执行Ansgar Wiechers在他的代码示例中所做的工作,但是使用加速器而不是cmdlet。像这样..。
[PSCustomObject]@{
'DOCNUM' = $Row.DOCNUM
'SOURCE' = $Row.DOCLOC
'DESTINATION' = $Row.DOCLOC -replace $srcPath, $dstPath
}希望能帮上忙
李
https://stackoverflow.com/questions/52693561
复制相似问题