我正在尝试在python中执行一个powershell脚本。我可以用一个简单的“Hello”脚本来证明它是有效的,但是现在我需要执行另一个由退休的同事编写的脚本。我不太熟悉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是否需要重写原始脚本以获得要调用的引用脚本?
发布于 2021-07-26 18:23:18
虽然可以将脚本中的./TSagentService.ps1替换为$PSScriptRoot/TSagentService.ps1,以便可靠地将脚本定位在与封闭脚本相同的文件夹中,但脚本中可能有其他代码假设脚本本身的位置也是工作目录,因此最好将工作目录显式地设置为目标脚本的目录。
如果您使用PowerShell (Core) 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"应用了Python代码,它调用powershell.exe
# -*- 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,这是非交互式调用的良好实践。
https://stackoverflow.com/questions/68534692
复制相似问题