在PowerShell中使用Start-Job和Invoke-WebRequest批量下载

时间:2017-09-11 11:43:40

标签: windows powershell batch-file

我已获得当前代码:

$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

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

有谁知道我做错了什么?

2 个答案:

答案 0 :(得分:0)

第一个值不在里面。因此,您应该使用 start-job

的param和argumentlist

试试这个:

$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

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

希望它有所帮助。

答案 1 :(得分:0)

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

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)"
    }
}