How can I pass variable colors to be printed from a python script by calling a powershell function.
function check($color){
Write-Host "I have a $color shirt"
}
import subprocess
color = "blue"
subprocess.call(["powershell.exe", '-Command', '&{. "./colortest.ps1"; & check(color)}'])
Above code results in below error
color : The term 'color' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:27
&{. "./colortest.ps1"; & check(color)}
~~~
CategoryInfo : ObjectNotFound: (color:String) [], CommandNotFoundException
FullyQualifiedErrorId : CommandNotFoundException
If I directly insert the actual color as a constant parameter, then I get the desired result but replacing it with a variable fails.
subprocess.call(["powershell.exe", '-Command', '&{. "./colortest.ps1"; & check("blue")}'])
Result
I have a blue shirt
CodePudding user response:
Using str.format
the code could be as follows. Note, when calling the PowerShell CLI with the -Command
parameter, there is no need to use & {...}
, PowerShell will interpret the string as the command you want to execute. There is also no need for &
(call operator) when calling your function (check
) and lastly, function parameters in PowerShell are either named (-Color
) or positional, don't use (...)
to wrap your parameters.
import subprocess
color = "blue"
subprocess.call([ 'powershell.exe', '-c', '. ./colortest.ps1; check -color {0}'.format(color) ])
CodePudding user response:
Your problem here at this part:
'&{. "./colortest.ps1"; & check(color)}'
is that you're passing the string color
to the function check
. you need to pass the value of the local variable color
instead. so you can use F-string.
subprocess.call(["powershell.exe", '-Command', f"&{. "./colortest.ps1"; & check({color})}"])