【问题标题】:Powershell foreach loop isn't exiting on third executionPowershell foreach 循环在第三次执行时没有退出
【发布时间】:2017-11-24 10:39:34
【问题描述】:

我有一个 powershell 脚本,它遍历 URL 的 SQL 表并收集网页上标签中的任何其他 URL。

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

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=localhost\SQLEXPRESS;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 后挂起并且不执行任何其他操作。

有人可以指点我如何调试它或我哪里出错了。

【问题讨论】:

  • 您是否尝试在 ISE 中调试您的脚本?这至少应该给你一个指示。在挂起的命令中使用 Verbose 开关应该会在此之后告诉您更多信息。
  • 是的,我做到了,它迭代并没有抛出任何错误,但仍然没有退出。当涉及到它在没有调试的情况下运行失败的 URL 时,它不会让我跨步,进入或退出。

标签: loops powershell foreach


【解决方案1】:

试试这个,

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

我有一个类似的问题,罪魁祸首是调用,它一直等到调用发生。所以给调用一个超时以跳过一些占用你时间的调用。

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

【讨论】:

  • 感谢您的建议,但不幸的是它没有奏效。我尝试将超时设置为 2 秒,然后放置了半小时,仍然没有完成。
  • 好的,作为一个新手修复尝试有一个调试器并在 foreach 循环中设置很多变量,并尝试找出代码到底哪里变得奇怪。我建议(如果可能的话)发布示例数据在这里,所以我们了解其中到底发生了什么。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2018-05-28
  • 1970-01-01
  • 2018-07-07
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多