qshinoの日記

Powershell関係と徒然なこと

WebClient

WebClient by PowerShell

Webclient classを使ってダウンロード

function download ( 
    [String]$dir = "c:\wk\poi", 
    [uri]$uri = "https://www.google.com/index.html")
{
  $file = Split-Path $uri.AbsolutePath -Leaf
  $bs = New-Object System.Net.WebClient
  $ret = $bs.DownloadFile( $uri, (Join-Path $dir $file))
  return $ret
}

Basic認証1

その一

function upload($user,$pw, $file, $uri){
  $cred = [system.Net]::NetworkCredential($user,$pw)
  $bs = New-Object system.Net.WebClient
  $bs.Credentials = $cred
  $site= $bs.DownloadFile($uri)

  return $site
}

Basic認証2

認証1でエラー401になる場合

function upload($user,$pw, $file, $uri){
  $bs = New-Object system.Net.WebClient
  $upw =  "{0}:{1}" -f $user, $pw
  $bytes = [System.Text.Encoding]::ASCII.GetBytes($upw)
  $b64 = [System.Convert]::ToBase64String($bytes)

$auth = [system.Net.HttpRequestHeader]::Authorization
$bs.Headers[$auth] = "Basic " + $b64
  $bs.UploadFile($uri, $file)
}

参考

Basic認証

http://qiita.com/muro/items/8b9f5886c56f7b6afd3c

http://qiita.com/ki02/items/575fc79c0acd3811902e

download

http://www.atmarkit.co.jp/fwin2k/win2ktips/995dlfile/dlfile.html

madn webclient

https://msdn.microsoft.com/ja-jp/library/system.net.webclient(v=vs.110).aspx

msdn httpRequestHeader

https://msdn.microsoft.com/ja-jp/library/system.net.httprequestheader(v=vs.110).aspx