How to while loop in Powershell were it reads the content in a file?

29 Views Asked by At

I can't find much documentation on this, but if we wanted to create a while loop, where it reads the content (from each line) in a file and passes that value into an executable command.

So the example is that I use PowerShell terminal to run a python script. The script requires parameters to be provided. One of the parameters to be provided is filenames. However, I'd like to write these filenames, as a list, into a document. Then use a PowerShell while loop to read each line of the document and push it to the executable command.

Is that possible?

This is the command I am running at the moment:

python .\retrieve_files.py -filename "filename1" "filename2" "filename3"

This isn't sufficient however if I have over 100 files to retrieve.

1

There are 1 best solutions below

3
forest-spells On

You can read filenames in specific directory using os. Just specify path to the directory.

import os


filenames_list = []
for file in os.listdir('path'):
    filenames_list.append(file)
    
output = 'filenames.txt'


with open(output, 'w') as f:
    for filename in filenames_list:
        f.write(filename + ',\n')