【问题标题】:Batch downloading with Start-Job and Invoke-WebRequest in PowerShell在 PowerShell 中使用 Start-Job 和 Invoke-WebRequest 进行批量下载
【发布时间】:2017-09-11 23:36:45
【问题描述】:

我有当前代码:

$installers = @{
    "vagrant.msi" = "https://releases.hashicorp.com/vagrant/2.0.0/vagrant_2.0.0_x86_64.msi";
    "chrome.exe" = "https://dl.google.com/tag/s/defaultbrowser/chrome/install/ChromeStandaloneSetup64.exe";
}

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

foreach ($i in $installers.GetEnumerator()) {
    Start-Job -ScriptBlock {
        Invoke-WebRequest $($using:i.Value) -Method Get -OutFile "$env:USERPROFILE\Downloads\$($using:i.Name)"
    }
}

Get-Job|Wait-Job

我相信这应该同时将两个文件下载到 Downloads。这两项工作似乎都在运行,但最后我只得到了chrome.exe

有谁知道我做错了什么?

【问题讨论】:

    标签: windows powershell batch-file


    【解决方案1】:

    第一个值没有进入。所以你应该使用 start-job

    的参数和参数列表

    试试这个:

    $installers = @{
        "vagrant.msi" = "https://releases.hashicorp.com/vagrant/2.0.0/vagrant_2.0.0_x86_64.msi";
        "chrome.exe" = "https://dl.google.com/tag/s/defaultbrowser/chrome/install/ChromeStandaloneSetup64.exe";
    }
    
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
    
    foreach ($i in $installers.GetEnumerator()) 
    {
        $value=$i.Value
        $Downloadpath="$env:USERPROFILE\Downloads\$($i.Name)"
        Start-Job -ScriptBlock {param($value,$Downloadpath)Invoke-WebRequest $value -Method Get -OutFile $Downloadpath} -ArgumentList $value,$Downloadpath
    }
    
    Get-Job|Wait-Job
    

    注意:似乎第一份工作失败了。只需交叉检查一次

    希望对你有帮助。

    【讨论】:

    • 谢谢,但似乎没有任何区别。
    • @SmallHadronCollider:我给出了原因。工作失败了。只有 Chrome 被下载。如果我使用任何其他 URL,那么它正在工作。
    • 第一个作业失败了,因为SecurityProtocol 行放错了位置。如果你将它移到ScriptBlock 内,它就可以工作。感谢您为我指明正确的方向。
    • @SmallHadronCollider:太好了。接受/赞成答案将是可观的。
    【解决方案2】:

    我需要在Start-Job 块内移动[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 行:

    foreach ($i in $installers.GetEnumerator()) {
        Start-Job -ScriptBlock {
            [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
            Invoke-WebRequest $($using:i.Value) -Method Get -OutFile "$env:USERPROFILE\Downloads\$($using:i.Name)"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 2018-01-02
      • 2020-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多