How to execute python script on every file recursively on windows

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.

Answer

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:FolderPath";
(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:PowerShellPScript.ps1" "C:Folder123678"

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:FolderPath";
(Get-ChildItem $src -Recurse -File).FullName | % { Process {
    Start-Process Python -ArgumentList "./convert.py $($_)" } };

Supporting Resources