简体   繁体   English

从Python调用时将参数传递给PowerShell脚本

[英]pass parameter to PowerShell script when calling from Python

From python I want to call a powershell script and pass a parameter to it 我想从python调用powershell脚本并将参数传递给它

The Powershell function header is listed here: Powershell函数头在这里列出:

Function Invoke-Neo4j
{
  [cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
  param (
    [Parameter(Mandatory=$false,ValueFromPipeline=$false,Position=0)]
    [string]$Command = ''
  )

Python - How do pass the parameter $Command = 'start' to the function from python? Python-如何将参数$ Command ='start'从python传递给函数? I can't seem to get it to work. 我似乎无法正常工作。

import subprocess
cmd = ['powershell.exe', '-ExecutionPolicy', 'RemoteSigned', '-File',
       'C:\\PathName\\Invoke-Neo4j.ps1']
returncode = subprocess.call(cmd)
print(returncode)

I couldn't make the Powershell command work from Python. 我无法从Python使用Powershell命令。 I actually found a .bat file with a command that works. 我实际上找到了一个.bat文件,该文件具有有效的命令。 I just inserted the 'start' parameter I call the bat file from python. 我刚刚插入了“ start”参数,我从python调用了bat文件。 It works like a charm. 它像一种魅力。 It's not optimal but it does the job for me. 这不是最佳选择,但可以为我完成工作。

SETLOCAL
Powershell -NoProfile -NonInteractive -NoLogo -ExecutionPolicy Bypass -Command "try { Unblock-File -Path '%~dp0Neo4j-Management\*.*' -ErrorAction 'SilentlyContinue' } catch {};Import-Module '%~dp0Neo4j-Management.psd1'; Exit (Invoke-Neo4j 'start')"
EXIT /B %ERRORLEVEL%

Running a script, in either PowerShell or Python, that only defines a function but does not call it has no other effect than defining function. 在PowerShell或Python中运行仅定义函数但不调用它的脚本,除了定义函数外没有其他作用。 The script needs to include a specific call to that function. 该脚本需要包含对该函数的特定调用。 In your case, you might as well put the logic at the top level of the script instead of inside a function then calling the function. 在您的情况下,您最好将逻辑放在脚本的顶层,而不是放在函数内部,然后调用该函数。 This would look like: 看起来像:

[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param (
    [Parameter(Mandatory=$false,ValueFromPipeline=$false,Position=0)]
    [string]$Command = ''
)
# rest of code not surrounded by { }
exit 0

Invoke the revised script from Python as you were initially doing and it should work properly. 像最初一样从Python调用修改后的脚本,它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM