Powershell foreach 循环在第三次执行时未退出



我有一个Powershell脚本,它循环访问URL的SQL表,并在网页上的标签中收集任何其他URL。

当 SQL 表中只有几个 URL 时,它似乎工作得很好,但 foreach 循环似乎在运行几次后停止工作并且表已经增长(但只有大约 250+ 行),之后它只是挂起,我不知道为什么。活动只是停止,foreach 循环永远不会退出。

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhostSQLEXPRESS;Database=PowerScrape;trusted_connection=true;"
$SqlConnection.Open()
$SqlCommand = New-Object System.Data.SQLClient.SQLCommand
$SqlCommand.Connection = $SqlConnection
$SqlSelectStatement = ("SELECT URL as url FROM dbo.CapturedURL WHERE NOT LEFT(Url,7) ='mailto:'")
$SqlCommand.CommandText = $SqlSelectStatement
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCommand
$SqlCommand.Connection = $SqlConnection
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($Dataset)
ForEach ($Row in $Dataset.Tables[0].Rows)
{
$Request = Invoke-WebRequest -Uri $Row[0] 
$UrlArray = $Request.Links | Select-Object -ExpandProperty href 
$UrlAuthority = $Request.BaseResponse | Select-Object -ExpandProperty ResponseUri | Select-Object -ExpandProperty Authority
ForEach ($Url in $UrlArray) 
{
If ($Url -like "/*") 
{
$ScrapedUrl = $UrlAuthority+$Url 
} 
Else    
{
$ScrapedUrl = $Url
}
If ($ScrapedUrl -notlike "#*"-and $ScrapedUrl -ne '' -and $ScrapedUrl -ne $null)
{
$SqlInsertStatement = "
BEGIN 
IF NOT EXISTS (SELECT * FROM CapturedUrl WHERE URL = '"+$ScrapedUrl+"')
BEGIN
INSERT CapturedURL (URL) VALUES ('"+$ScrapedUrl+"')
END   
END;"
$SqlCommand = $SqlConnection.CreateCommand()
$SqlCommand.CommandText = $SqlInsertStatement
$SqlCommand.ExecuteNonQuery()
}
}
}

例如,当我在表中插入一行时,例如 http://rouge.jneen.net(不是我的网站,只有一个我喜欢的网站,只有几个链接开始),还会插入另外六个 URL。然后,当我再次运行它时,它会转到表中的所有 URL 并插入 279 个 URL。这很好,但是当我第三次运行它时,它在 Uri https://github.com/edwardloveall/portfolio 上调用 Invoke-WebRequest 后挂起并且不执行任何其他操作。

有人可以指出我如何调试它或我出错的方向吗?

试试这个,

$Request = Invoke-WebRequest -Uri $Row[0] -TimeoutSec 30

我有一个类似的问题,罪魁祸首被调用,它一直等到调用发生。因此,请为调用超时,以跳过一些占用您时间的调用。

此外,我建议您尝试工作流并使用For eac Parallel执行此操作以加快执行速度。

最新更新