Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading