【问题标题】:PowerShell - How to run a command that depends on the start of a service?PowerShell - 如何运行取决于服务启动的命令?
【发布时间】:2019-03-05 14:21:44
【问题描述】:

我有一个脚本,可以选择发送电子邮件;这需要 stunnel 运行。 如果服务正在运行,然后我执行脚本,它会完美运行:

cmd /c "blat -subject `"Test`" -body `"Test`" -ss -base64 -html -r -noh2 -to $emailto -u $username -attach $anexo -pw $password -f $username -server 127.0.0.1:25 -debug -log $blatLog"

但是,如果我尝试在脚本中启动服务,它不起作用,没有错误,只是没有发送电子邮件。

Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -Command `"
    Start-Service stunnel;
    cmd /c ""blat -subject `"Hello`" -body `"Hi`" -ss -base64 -html -r -noh2 -to $emailto -u $username -pw $password -f $username -server 127.0.0.1:25 -debug"" | Out-Null;
    Stop-Service stunnel;
`"" -Wait -Verb RunAs

脚本做了很多事情,除了启动服务外,没有一个需要管理员运行。 我知道我可以保持服务运行,但为什么它不起作用?

【问题讨论】:

  • 服务完全运行可能需要一些时间。发送邮件前检查状态如何?
  • @lit 你是对的;我刚刚添加了“Start-Sleep -seconds 10;”启动服务后,现在它可以工作了。谢谢!!
  • 只是休眠并不能处理服务无法运行的情况。您应该使用Get-Service 并检查返回对象的.status;见Get-Service at Microsoft Docs
  • 请注意Start-service 通常是同步的,因此stunnel 服务似乎过早地报告正在启动并运行。 Start-Sleep 是一种不可靠的同步机制,所以我建议你寻找更可靠的方法来测试服务是否可以使用;但是,(Get-Service stunnel).Status 可能还不够。

标签: powershell


【解决方案1】:

所以,这是我想出的解决方案:

$ScriptBlock = {
    function CheckStunnel {
        $t = New-Object System.Net.Sockets.TcpClient '127.0.0.1', 25;
        while ($t.Connected -ne 'True') {
            If ((Get-Service stunnel).Status -ne 'Running') { Start-Service stunnel }
            Start-Sleep -seconds 3;
            $t = New-Object System.Net.Sockets.TcpClient '127.0.0.1', 25;
        }
    }
}
Start-Process PowerShell "-NoProfile -ExecutionPolicy Bypass -Command `"
    & {$ScriptBlock CheckStunnel}
    Blat -subject `"Test`" -body `"Test`" -ss -base64 -html -r -noh2 -to $emailto -u $username -attach $anexo -pw $password -f $username -server 127.0.0.1:25 -debug -log $blatLog;
    if ($LASTEXITCODE -eq 0) { Stop-Service stunnel }
`"" -Verb RunAs

既然stunnel的作用是打开一个端口,那我只需要检查一下端口是否打开。 现在一切正常。

感谢您的帮助!

【讨论】:

    猜你喜欢
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2021-06-30
    • 1970-01-01
    相关资源
    最近更新 更多