Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing command line arguments to a .ps1 file from Python's subprocess.Popen() method

I would like to pass command line arguments to to the file "my script.ps1", as well as pass NoProfile to the PowerShell executable.

The scripts (c:/temp/my script.ps1) content is:

param($param1, $param2, $param3)
$PSBoundParameters.Keys.count
$param1
$param2
$param3

I want to call this script within Python 3, I tried a number of quoting approaches and they are all failing. I can only call the script without arguments. The following is but some of the things I tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import subprocess
#subprocess.Popen(['pwsh','-file "C:\Temp\my script.ps1" "cat" "dog"'])        #Console Window Error -->  The argument '-file "C:\Temp\my script.ps1" "cat"' is not recognized as the name of a script file
#subprocess.Popen(['pwsh','"C:\Temp\my script.ps1" "cat" "dog"'])              #Console Window Error -->  The argument '"C:\Temp\my script.ps1" "cat"' is not recognize
#subprocess.Popen(['pwsh -file ','"C:\Temp\my script.ps1" "cat" "dog"'])       #Console window does not seem to open
subprocess.Popen(['pwsh','C:\Temp\my script.ps1'])                             #This is the only test that worked

input("Press enter to exit;")                                                  #Keep the console window open

I can run the ps1 just fine on a PowerShell Terminal:

pwsh 'C:\Temp\my script.ps1' 'cat' 'dog'
2
Cat
Dog

Or:

pwsh -nologo -noprofile -file 'C:\Temp\my script.ps1' 'cat' 'dog'
2
Cat
Dog

I am working with PowerShell 7 and Python 3 on windows.

Any help would be greatly appreciated!

>Solution :

Specify the arguments to pass through to the script as separate array elements; ditto for -NoProfile.

subprocess.Popen(['pwsh', '-NoProfile', 'C:\Temp\my script.ps1', 'cat', 'dog'])
  • The above is the equivalent of calling
    pwsh -NoProfile "C:\Temp\my script.ps1" cat dog e.g. from a PowerShell session.

  • -File is implied with pwsh, the PowerShell (Core) CLI (whereas powershell.exe, the Windows PowerShell CLI, defaults to -Command). If you were to specify it, you’d have to place it in a separate array element just before the element specifying the script file path.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading