tech.guitarrapc.cóm

Technical updates

PowerShellでwget のようにファイルダウンロードをしたい

Linuxにはwgetcurlなど、ダウンロードに便利なコマンドがあります。 PowerShellはファイルダウンロードの際に.NETを記述、叩かなくてはいけないのでしょうか? PowerShell 3.0からはそんなことありません。

Invoke-WebRequestを使うことで、ファイルダウンロードが簡単になりました。 今回、サクッとつかうのにfunctionでラップしたので、サンプルをどうぞ。

基本記述

基本的にはこの形式でファイルダウンロードが可能です。

Invoke-WebRequest -Uri 対象URI -OutFile 保存するローカルパス

functionにしてみる

GitHubに置いておきました。

guitarrapc/PowerShellUtil - Invoke-DownloadFile/Invoke-DownloadFile.ps1 | GitHub

#Requires -Version 3.0

function Invoke-DownloadFile{

  [CmdletBinding()]
  param(
    [parameter(Mandatory,position=0)]
    [string]
    $Uri,

    [parameter(Mandatory,position=1)]
    [string]
    $DownloadFolder,

    [parameter(Mandatory,position=2)]
    [string]
    $FileName
  )

  begin
  {
    If (-not(Test-Path $DownloadFolder))
    {
      try
      {
        New-Item -ItemType Directory -Path $DownloadFolder -ErrorAction stop
      }
      catch
      {
        throw $_
      }
    }

    try
    {
      $DownloadPath = Join-Path $DownloadFolder $FileName -ErrorAction Stop
    }
    catch
    {
      throw $_
    }
  }

  process
  {
    Invoke-WebRequest -Uri $Uri -OutFile $DownloadPath -Verbose -PassThru
  }

  end
  {
    Get-Item $DownloadPath
  }

}

利用方法

保存先のが存在しない場合は作ったりしてくれるようにしました。

たとえば、SumoLogicからWindows用のインストーラをダウンロードしてD:\hoge\SumoCollector_WindowsSetup.exeとして保存する場合はこのようになります。

Invoke-DownloadFile -Uri "https://collectors.sumologic.com/rest/download/windows" -DownloadFolder "D:\hoge" -FileName "SumoCollector_WindowsSetup.exe"