0

I am trying to do something I thought would be trivial.
I just wanted to declare a function as that

function mds {
python -m "blabla" $args
}

but it's just not working under Powershell.
I got this error:

mds : The term 'python -m os:String' is not recognized as the name of a cmdlet, function, script file, or operable program. Ch
eck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

As I understand Powershell takes the whole python -m "asdfadsf" as command, but why? And how can I workaround it ?

1
  • meterr - Simply try Start-Process python "-m blabla $args" -Wait or something to that effect. Commented Jan 6, 2020 at 21:49

1 Answer 1

1

PowerShell has no idea what that python code is, hence the error. Also, there are several reserved words, variables (automatic and default). Point of note ...

$args

... is one of those, so, not one you can use in your code for your own use.

$args Automatic Variable in PowerShell ‘$args’ is an Automatic variable in PowerShell that contains an array of the undeclared parameters passed to a script

# iterating through the arguments
# and performing an operation on each
$args | ForEach-Object { $_*2 }
"Argument count: $($args.Count)"
"First Argument : $($args[0])"
"Second Argument : $($args[1])"
"Last Argument : $($args[-1])"
$args.GetType() # get the type of the object

Also, python notwithstanding, this is not the way to call external commands in PowerShell. There are well-documented resources regarding how to call external commands from PowerShell scripts/functions. For example:

PowerShell: Running Executables

Solve Problems with External Command Lines in PowerShell

Top 5 tips for running external commands in Powershell

Execution of External Commands in PowerShell Done Right

Using Windows PowerShell to run old command-line tools (and their weirdest parameters)

See also about Redirection

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_redirection?view=powershell-6

https://stackoverflow.com/questions/19220933/powershell-pipe-external-command-output-to-another-external-command

Quoting specifics

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules https://trevorsullivan.net/2016/07/20/powershell-quoting

Lastly...

PowerShell Scripting Guide to Python – Passing Command-Line Arguments

About Automatic Variables

All in all, you'd end up with something like this...

$PythonArgs = @('-m', 
'pip',
'install', 
'--upgrade'
'pip')

function mds {
    & 'python.exe' $PythonArgs
}

mds

# Results
<#
Requirement already up-to-date: pip in d:\scripts\python\pycharmprojects\test\venv\lib\site-packages (19.3.1)
#>

You must log in to answer this question.

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