Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a string variable to a PowerShell function from python

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
like image 343
tee Avatar asked Aug 29 '26 17:08

tee


2 Answers

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) ])
like image 87
Santiago Squarzon Avatar answered Sep 01 '26 05:09

Santiago Squarzon


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})}"])
like image 37
Mohamed Mostafa Avatar answered Sep 01 '26 05:09

Mohamed Mostafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!