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:
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 doge.g. from a PowerShell session. -
-Fileis implied withpwsh, the PowerShell (Core) CLI (whereaspowershell.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.