1

I normally use a PowerShell script to download bulk CSV of images, but I have a new URL that displays the images very oddly. Could I modify this script to allow for these image URLs?

Example URLs:

https://www.example.com/core/media/media.nl?id=12&c=23&h=b944f2f81326d0bb
https://www.example.com/core/media/media.nl?id=15&c=42&h=7ed23c91f3574fc9

and the current script...

[Reflection.Assembly]::LoadFile(
    'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Web.dll') | Out-Null 

$FileName = "C:\Temp\test.txt";
$Loc = "C:\Temp\Images\"
$ImageName = ""

$wc = New-Object System.Net.WebClient

$content = Get-Content $FileName
foreach ($line in $content) {
    $Image = $Loc + $line.Substring($line.LastIndexOf("/") + 1)
    $url = $line

    Write-Host $url
    Write-Host $Image

    $wc.DownloadFile($url, $Image)
}

Write-Jost "Finished successfully."
0

1 Answer 1

1

A file name on Windows can't contain ?, *, ", \ characters, so filter them out:

$Image = $Loc + ($line.Substring($line.LastIndexOf("/") + 1) -replace '[?*"\\]', '_')

To get the real redirected file name from a dynamic URL process the Content-Disposition header:

$tmp = [IO.Path]::GetTempFileName()
$wc.DownloadFile($url, $tmp)

$Image = "$($wc.ResponseHeaders['Content-Disposition'])" -replace '^.*?filename=', ''
if (!$Image) {
    $Image = $line.Substring($line.LastIndexOf("/") + 1) -replace '[?*"\\]', '_'
}
Move $tmp (Join-Path $Loc $Image)
Sign up to request clarification or add additional context in comments.

3 Comments

Ah, I'm sorry, we were looking at this differently. While yours works (after renaming it with a jpg extension), I was looking to pull the real image info. What I mean by that, is if you enter the top URL above, and right click, save as.... you get the actual file name - 027789-352816.jpg. Is there any way Powershell can grab that?
Works - oddly, how I have it integrated, it always throws these Exception calling "DownloadFile" with "2" Parameter name: address" At line:15 char:1 + $wc.DownloadFile($url, $tmp) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified + FullyQualifiedErrorId : ArgumentNull Cannot index into a null array. At line:17 char:13 + $Image = "$($wc.ResponseHeaders['Content + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOpera + FullyQualifiedErrorId : NullArray
I have no idea. Debug the code in PowerShell ISE: open the script, click a line inside the code, press F9 to set a breakpoint, run the script (F5), then step through the code (F10) and point the mouse over the variables to see the values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.