繁体   English   中英

我正在尝试在 python 中执行一个引用另一个 powershell 脚本的 powershell 脚本

[英]I am trying to execute a powershell script in python that references another powershell script

我正在尝试在 python 中执行一个 powershell 脚本。 我能够使用一个简单的“Hello World”脚本来证明它有效,但我现在需要执行另一个由退休同事编写的脚本。 我对 powershell 脚本不是很熟悉。 所有脚本当前都位于同一目录中。 有问题的脚本调用另一个 powershell 脚本。 从 powershell 命令行调用时,这也可以正常工作。 python 脚本如下所示:

# -*- coding: iso-8859-1 -*-
import subprocess, sys

cmd = 'powershell.exe'
dir = 'C:\Agent\\agentStatus.ps1'

p = subprocess.Popen([cmd,
              dir],
              stdout=sys.stdout)
p.communicate()

powershell 脚本如下所示:

Write-Host -NoNewLine "Agent service is "
./TSagentService.ps1 -Status
if ((Get-Process "endpoint_runner" -ErrorAction SilentlyContinue) -eq $null) {
    Write-Output "Agent is Not Running"
} else {
    Write-Output "Agent is Running"
}

我在调用时得到的错误是这样的:

./TSagentService.ps1 : The term './TSagentService.ps1' 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 C:\agentStatus.ps1:3 char:1
+ ./TSagentService.ps1 -Status
+ ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (./TSagentService.ps1:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

我是否需要重写原始脚本才能调用引用的脚本?

虽然你可以代替./TSagentService.ps1$PSScriptRoot/TSagentService.ps1脚本以便可靠地定位一个脚本在同一文件夹作为封闭剧本,有可能是在脚本(S)等代码,假定脚本自己的位置也是工作目录,因此最好将工作目录明确设置为目标脚本的目录

如果你正在使用PowerShell的(核心)V6 +以其pwsh.exe CLI ,您可以利用其新的优势-WorkingDirectory-wd )参数这样做; 例如(使用 no-shell / cmd.exe / PowerShell 语法):

pwsh -wd c:/path/to -file c:/path/to/script.ps1

Windows PowerShell 中,使用powershell.exe-Command ( -c ) 参数在调用脚本之前放置一个Set-Location调用; 例如:

powershell -c "Set-Location c:/path/to; & ./script.ps1"

应用了调用powershell.exe Python 代码:

# -*- coding: iso-8859-1 -*-
import subprocess, sys, pathlib

cmd = 'powershell.exe'
script = 'C:\Agent\\agentStatus.ps1'
dir = pathlib.Path(script).parent

p = subprocess.Popen(
  [
    cmd,
    '-noprofile',
    '-c',
    'Set-Location \"{}\"; & \"{}\"'.format(dir, script)
  ],
  stdout=sys.stdout
)
p.communicate()

请注意,我还添加了-noprofile ,这是非交互式调用的好习惯。

暂无
暂无

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

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