Monday, August 03, 2020

PowerShell and passing command-line arguments to external scripts

I like PowerShell a lot, but occasionally you run into something that seems mind-bendingly over-engineered. The simple act of calling an external script and passing command-line arguments to it is one of those things.

To avoid wasting any more of your time, here is the best way I have found to do it.

I will call the following Python script my_script.py from PowerShell, which simply prints out the arguments passed to Python:

import sys

for i in range(len(sys.argv)):
print("my_script args: " + str(i) + ": " + str(sys.argv[i]))

The script is called from PowerShell by putting the Python command-line arguments into an array and passing them to the external script using the Splat operator.

# Put Python command-line arguments into an array
$cmd_args = @("c:\temp\my_script.py", "-f", "c:\myfile.txt", "-t", "5")

# Call the Python executable, supplying arguments using the Splat operator
& python.exe @cmd_args

Which produces the expected output:

my_script args: 0: c:\temp\my_script.py
my_script args: 1: -f
my_script args: 2: c:\myfile.txt
my_script args: 3: -t
my_script args: 4: 5


No comments: