1

So I have a python command that takes a file path as a command line argument. Let's say convert.py.

On Linux I'm using the following script to run it on every file in a folder, recursively, using glob

for f in $1/**/*
do
  python ./convert.py $f
done

Which I can call like sh ./script.sh src.

Is there any way to do this on Windows? I found this which is close but I didn't quite get it.

1 Answer 1

1

A quick idea is to use Get-ChildItem with the -Directory and -Recurse options and use Start-Process and its -ArgumentList option to execute the python script passing it the full directory path.

1. Simple script (use to test specific folder(s))

$src = "C:\Folder\Path";
(Get-ChildItem $src -Directory -Recurse).FullName | % { Process {
    Start-Process Python -ArgumentList "./convert.py $($_)" } }; 

2. PowerShell script with execution arg value

$src = $args[0]; 
(Get-ChildItem $src -Directory -Recurse).FullName | % { Process {
    Start-Process Python -ArgumentList "./convert.py $($_)" } };

Executing the above #2 PowerShell script

powershell.exe -ExecutionPolicy Bypass -File "C:\PowerShell\PScript.ps1" "C:\Folder\123\678"

3. One more example (recursive files)

Note: In case the Python script needs the file path passed to it, use this example with the -File parameter this will pass the file paths. I'm not sure what the Python script is doing though.

$src = "C:\Folder\Path";
(Get-ChildItem $src -Recurse -File).FullName | % { Process {
    Start-Process Python -ArgumentList "./convert.py $($_)" } };

Supporting Resources

6
  • My understanding is that glob and the wildcards are for directory paths and traversing to get full paths. Here are a couple equilevant PowerShell examples you might find helpful. Jun 13, 2021 at 22:46
  • Just in case you do need the python script to be passed the full file paths rather than the path only, I added #3 example to show how that'd work. Jun 14, 2021 at 2:02
  • why do you always use Process{} inside a foreach?
    – SimonS
    Jun 14, 2021 at 8:23
  • 1
    Got it working, I was referencing the file paths incorrectly and needed to remove the - Directory argument. Also needed to add the -NoNewWindow so that it doesn't open a hundred windows when I run the command. Thanks a lot for the help.
    – ManavM
    Jun 14, 2021 at 11:30
  • 1
    @SimonS... It's out of habit and for a performance increase at times. Ever since I read up on it once per a comment someone left somewhere with a link, I've been doing that. I tested it out with Measure-Command for some loops and confirmed it indeed is faster in some instances. I think I do it out of habit more than anything now but I'm not aware of any issue is causes leaving it if it doesn't increase the speed. I read a better read on it once but cannot find, but see here for example powershell.one/tricks/performance/pipeline Jun 14, 2021 at 13:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .