I am trying to get a powershell script that I can call with one (or two) params.
Ideally I would like to pass only one paramter, the $Url and expect the script to figure out the filename and then download to that filename.
IF it does not figure out a filename, I can optionally pass a second parameter the $FolderPath
# get-FileFromUri.ps1
function get-FileFromUri {
param(
[Parameter(Mandatory = $true,Position = 0,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true)]
[string]
[Alias('Uri')]
$Url,
[Parameter(Mandatory = $false,Position = 1)]
[string]
[Alias('Folder')]
$FolderPath
)
process {
try {
# resolve short URLs
$req = [System.Net.HttpWebRequest]::Create($Url)
$req.Method = "HEAD"
$response = $req.GetResponse()
$fUri = $response.ResponseUri
$filename = [System.IO.Path]::GetFileName($fUri.LocalPath);
$response.Close()
# download file
$destination = (Get-Item -Path ".\" -Verbose).FullName
if ($FolderPath) { $destination = $FolderPath }
if ($destination.EndsWith('\')) {
$destination += $filename
} else {
$destination += '\' + $filename
}
$webclient = New-Object System.Net.webclient
$webclient.downloadfile($fUri.AbsoluteUri,$destination)
Write-Host -ForegroundColor DarkGreen "downloaded '$($fUri.AbsoluteUri)' to '$($destination)'"
} catch {
Write-Host -ForegroundColor DarkRed $_.Exception.Message
}
}
}
get-FileFromUri $Url $FolderPath
But this script does not seem to work? If i call it absolutely nothing useful seems to happen? Where did I go wrong? I call it from a powershell prompt as
.\get-FileFromUri.ps1 'http://www.mywebsite.com/downloads/myfile1.zip'
But I get :
.\get-FileFromUri.ps1 'http://www.mywebsite.com/downloads/myfile1.zip'
get-FileFromUri : Cannot bind argument to parameter 'Url' because it is an empty string.
At .\get-FileFromUri.ps1:39 char:17
+ get-FileFromUri $Url $FolderPath
+ ~~~~
+ CategoryInfo : InvalidData: (:) [get-FileFromUri], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,get-FileFromUri
How do I pass my params to this script? A simple wget in *nix gives me the file. and even giving it a filename as second argument has seemingly no effect. How do I improve this, so it takes paramters and actually calls the function with those two params pased on the cmd line?
.\get-FileFromUri.ps1 'http://www.mywebsite.com/downloads/myfile1.zip' 'c:\temp\myfile1.zip'
OK so I added -ArgumentList whe calling it, as in
and I stil get seemingly same error: