在PowerShell中创建批处理作业

时间:2020-03-05 18:49:15  来源:igfitidea点击:

想象一下一个DOS样式的.cmd文件,该文件用于以正确的顺序启动相互依赖的窗口化应用程序。

例子:
1)通过调用带有参数的exe启动服务器应用程序。
2)等待服务器初始化(或者固定时间)。
3)通过调用带有参数的exe启动客户端应用程序。

在PowerShell中完成这种批处理作业的最简单方法是什么?

解决方案

回答

要在启动应用程序之间等待10秒钟,请尝试

launch-server-application serverparam1 serverparam2 ...
Start-Sleep -s 10
launch-client-application clientparam1 clientparam2 clientparam3 ...

如果要创建脚本并传递参数,请创建一个名为runlinkedapps.ps1(或者其他内容)的文件,其中包含以下内容:

launch-server-application $args[0] $args[1]
Start-Sleep -s 10
launch-client-application $args[2] $args[3] $args[4]

或者,但是我们选择在用于运行runlinkedapps.ps1的行上分发服务器和客户端参数。如果需要,我们甚至可以在此处传递延迟,而不是硬编码" 10"。

请记住,.ps1文件必须位于Path上,否则我们必须在运行它时指定其位置。 (哦,如果没有,我假设启动服务器应用程序和启动客户端应用程序在路径上,那么我们还需要指定它们的完整路径。)

回答

请记住,PowerShell可以访问.Net对象。 Blair Conrad建议的启动睡眠可以由对服务器进程的WaitForInputIdle的调用来代替,这样我们就可以在启动客户端之前知道服务器何时就绪。

$sp = get-process server-application
$sp.WaitForInputIdle()

我们还可以使用Process.Start启动该过程,并使其返回确切的Process。然后,我们不需要get-process。

$sp = [diagnostics.process]::start("server-application", "params")
$sp.WaitForInputIdle()
$cp = [diagnostics.process]::start("client-application", "params")

回答

@Lars Truijens建议

Remember that PowerShell can access
  .Net objects. The Start-Sleep as
  suggested by Blair Conrad can be
  replaced by a call to WaitForInputIdle
  of the server process so you know when
  the server is ready before starting
  the client.

这比睡眠固定(或者通过参数提供)的时间量更优雅。然而,
WaitForInputIdle

applies only to processes with a user
  interface and, therefore, a message
  loop.

因此,根据启动服务器应用程序的特性,这可能不起作用。但是,正如Lars向我指出的那样,该问题涉及一个窗​​口化的应用程序(当我阅读该问题时我错过了),因此他的解决方案可能是最好的。