0

I want to run a pretty basic script that has a list of executables (different python versions in this case) that runs them one by one in a loop as part of a command.

Example:

$py39 = python # can be full path to an .exe if needed
$py310 = python3.10
$py311 = python3.11
$pythons = $py39,$py310,$py311

Foreach ($py in $pythons)
{

$py --version

$py -c "print('hello world')"

}

"python", "python3.10", "python3.11" all launch their respective python version when I run it myself correctly.

When I run the script I get these errors. How do I make it work?

+ $py --version
+       ~~~~~~~
Unexpected token 'version' in expression or statement.

+ $py -c "print('hello world')"
+     ~~
Unexpected token '-c' in expression or statement.
1

1 Answer 1

2

You need the & operator to run it as a system command rather than a ps expression I guess:

$py39 = "python"      # Full path to the executable if needed
$py310 = "python3.10"
$py311 = "python3.11"
$pythons = $py39, $py310, $py311

foreach ($py in $pythons) {
    & $py --version          # Use the & operator to run the command
    & $py -c "print('hello world')"  # Same here for -c
}
Sign up to request clarification or add additional context in comments.

2 Comments

On a side note I suggest uswing more meaningful names expliciting when a variable is a collection and when its an element of a collection: foreach($PythonExe in $PythonPit) is much easier to understand IMHO
It might be good to check to see if the command is available in the path. Get-Command -Name $py; if (-not $?) { Write-Host 'Command $py not found.' }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.