如何将字符串变量从 python 传递给 PowerShell 函数

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

如何通过调用 powershell 函数传递要从 python 脚本打印的可变颜色。

function check($color){
    Write-Host "I have a $color shirt"
}
import subprocess
color = "blue"
subprocess.call(["powershell.exe", '-Command', '&{. "./colortest.ps1"; & check(color)}'])

以上代码导致以下错误

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

如果我直接将实际颜色作为常量参数插入,那么我会得到所需的结果,但用变量替换它会失败。

subprocess.call(["powershell.exe", '-Command', '&{. "./colortest.ps1"; & check("blue")}'])

结果

I have a blue shirt

你这部分的问题:

'&{. "./colortest.ps1"; & check(color)}'

是您将字符串 color 传递给函数 check。您需要传递局部变量 color 的值。所以你可以使用 F-string.

subprocess.call(["powershell.exe", '-Command', f"&{. "./colortest.ps1"; & check({color})}"])

使用 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,不要使用 (...) 来包装您的参数。

import subprocess
color = "blue"
subprocess.call([ 'powershell.exe', '-c', '. ./colortest.ps1; check -color {0}'.format(color) ])