windowspowershellforeachwget

Can I get this FOREACH loop to work in Windows Powershell?


I'm trying to use a foreach loop in Windows Powershell to download some images and I think I'm close, but I can't seem to get it right.

The command:

foreach ($name in @('avatar_1', 'avatar_2', 'avatar_3', 'avatar_4', 'avatar_5', 'avatar_6', 'avatar_7', 'thumbnail_1'))
>> {
>> wget https://raw.githubusercontent.com/flutter/codelabs/main/animated-responsive-layout/step_04/assets/$name.png -O $name.png
>> }

It seems to loop through the list, but it just results in the below for each item:

StatusCode        : 200
StatusDescription : OK
Content           : {137, 80, 78, 71...}
RawContent        : HTTP/1.1 200 OK
                    Connection: keep-alive
                    Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox
                    Strict-Transport-Security: max-age=31536000
                    X-Content-Type-Options: nosniff
                    ...
Headers           : {[Connection, keep-alive], [Content-Security-Policy, default-src 'none'; style-src 'unsafe-inline'; sandbox], [Strict-Transport-Security, max-age=31536000],
                    [X-Content-Type-Options, nosniff]...}
RawContentLength  : 61683

I know the command works as wget https://raw.githubusercontent.com/flutter/codelabs/main/animated-responsive-layout/step_04/assets/avatar_1.png -O avatar_1.png will download the image. I'm not sure if I'm using the $name variable correctly in the foreach loop. I don't really use Powershell that often but ran into the command during a codelab and I was interested in getting it to work.


Solution

  • Here's the updated version of your script. This worked fine for me.

    foreach ($name in @('avatar_1', 'avatar_2', 'avatar_3', 'avatar_4', 'avatar_5', 'avatar_6', 'avatar_7', 'thumbnail_1'))
    {
        $url = "https://raw.githubusercontent.com/flutter/codelabs/main/animated-responsive-layout/step_04/assets/${name}.png"
        $outputFile = "${name}.png"
        Invoke-WebRequest $url -OutFile $outputFile
    }