问题描述
我正在尝试在Powershell中执行功能或脚本块,并为执行设置超时.
I am trying to execute a function or a scriptblock in powershell and set a timeout for the execution.
基本上我有以下内容(转换为伪代码):
Basically I have the following (translated into pseudocode):
function query{
#query remote system for something
}
$computerList = Get-Content "C:\scripts\computers.txt"
foreach ($computer in $computerList){
$result = query
#do something with $result
}
该查询的范围可以从使用Get-WmiObject的WMI查询到HTTP请求,并且脚本必须在混合环境中运行,包括Windows和Unix机器(均不具有HTTP接口).因此,某些查询必然会挂起或花费很长时间才能返回.在追求优化的过程中,我写了以下内容:
The query can range from a WMI query using Get-WmiObject to a HTTP request and the script has to run in a mixed environment, which includes Windows and Unix machines which do not all have a HTTP interface.Some of the queries will therefore necessarily hang or take a VERY long time to return.In my quest for optimization I have written the following:
$blockofcode = {
#query remote system for something
}
foreach ($computer in $computerList){
$Job = Start-Job -ScriptBlock $blockofcode -ArgumentList $computer
Wait-Job $Job.ID -Timeout 10 | out-null
$result = Receive-Job $Job.ID
#do something with result
}
但是不幸的是,工作似乎要承担很多开销.在我的测试中,以1.066秒(根据$ blockofcode中的计时器)执行的查询在作为Job执行时花了6.964秒才能返回结果.当然可以,但是我真的想减少这些开销.我也可以一起开始所有工作,然后等待它们完成,但是这些工作仍然可能会挂起或花很多时间来完成.
But unfortunately jobs seem to carry a LOT of overhead. In my tests a query that executes in 1.066 seconds (according to timers inside $blockofcode) took 6.964 seconds to return a result when executed as a Job. Of course it works, but I would really like to reduce that overhead. I could also start all jobs together and then wait for them to finish, but the jobs can still hang or take ridiculous amounts to time to complete.
那么,问题来了:有什么方法可以执行一个语句,函数,脚本块甚至是一个脚本,但其超时时间不包括作业所带来的开销?如果可能的话,我想并行运行命令,但这不是一个大问题.
So, on to the question: is there any way to execute a statement, function, scriptblock or even a script with a timeout that does not comprise the kind of overhead that comes with jobs? If possible I would like to run the commands in parallel, but that is not a deal-breaker.
任何帮助或提示将不胜感激!
Any help or hints would be greatly appreciated!
在混合的Windows/unix环境中运行Powershell V3
running powershell V3 in a mixed windows/unix environment
推荐答案
我认为您可能想使用Powershell运行空间进行调查:
I think you might want to investigate using Powershell runspaces:
这篇关于Powershell命令超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!