Powershell을 이용하여 Linux의 wget과 같이 Web (http, ftp) 에서 File을 다운로드하고 업로드하는 스크립트를 만들어 보자.
.Net의 WebClient를 사용하면 간단하다.
Get-WebFile.ps1
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
[String[]]$FileURLs,
[String]$SavePath = (Get-Location),
[String]$Username,
[String]$Password
)
if ( -not (Test-Path $SavePath))
{
return
}
foreach ($FileURL in $FileURLs)
{
$Pieces = $FileURL.Split("/")
$FileName = $Pieces[$Pieces.Count - 1]
$FilePath = Join-Path $SavePath $FileName
$Client = New-Object System.Net.WebClient
if (($Username -ne $null) -and ($Password -ne $null))
{
$Client.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
}
Write-Host ("[Download] {0} -> {1} ..." -f $FileURL, $FilePath) -NoNewline
$Client.DownloadFile($FileURL, $FilePath)
Write-Host " Finish"
}
핵심은 WebClient 개체를 만들고 DownloadFile 메서드를 호출 하는 것.
Upload도 마찬가지로 UploadFile 메서드를 호출 하면 된다.
Add-WebFile.ps1
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]
[String[]]$Files,
[Parameter(Mandatory=$true, Position=1)]
[String]$TargetPath,
[String]$Username,
[String]$Password
)
foreach ($File in $Files)
{
if (Test-Path $File)
{
$FileName = (Get-ChildItem $File).Name
if ($TargetPath[$TargetPath.Length - 1] -ne "/") { $TargetPath += "/" }
$TargetFullPath = ("{0}{1}" -f $TargetPath, $FileName)
$Client = New-Object System.Net.WebClient
if (($Username -ne $null) -and ($Password -ne $null))
{
$Client.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
}
Write-Host ("[Upload] {0} -> {1} ..." -f $File, $TargetFullPath) -NoNewline
$Client.UploadFile($TargetFullPath, $File)
Write-Host " Finish"
}
else
{
Write-Host ("Wrong File Path : {0}" -f $File)
}
}
이름 정하기가 까다롭다. Get-Verb 안에서 동사를 선택 하는데 Download, Upload 는 없으므로 Get , Add를 사용 했는데 적절 한지 모르겠다. Import, Export도 고려 해 봤지만 wget 명령이 생각 나서 Get은 쓰고 싶었고, 그렇다고 Upload를 Set으로 하는것도 마음에 안든다. Update 가 더 가까운 의미 인것 같기도 하다.
