[英]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.