向batch / powershell添加超时 [英] adding a timeout to batch/powershell
问题描述
$fullnamexp = ((net user $winxp /domain | Select-String "Full Name") -replace "Full Name","").Trim();
如果找不到 $ winxp
命令将挂起,有一个超时,我可以使用这个使它在5-10秒后移动?不确定我会把它放在哪里。
If $winxp
cannot be found, the command will hang, is there a timeout I can use with this to make it move on after 5-10 seconds? Not sure where I would put it.
编辑 - 我使用这个来拉用户名:
Edit- I use this to pull the username:
$reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $tag1)
$key = $reg.OpenSubKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon')
$winxp = $key.GetValue('DefaultUserName') -replace '^.*?\\'
$ winxp
是一个登录名,例如 ajstepanik
那么我把它放入: $ fullnamexp =((net user $ winxp / domain | Select-StringFull Name)-replaceFull Name,)Trim c $ c>
$winxp
is then a login name such as ajstepanik
then I put it into: $fullnamexp = ((net user $winxp /domain | Select-String "Full Name") -replace "Full Name","").Trim();
1.21.2014更新
$timeoutSeconds = 5
$code = {
((net user $winxp /domain | Select-String "Full Name") -replace "Full Name","").Trim(); # your commands here, e.g.
}
$j = Start-Job -ScriptBlock $code
if (Wait-Job $j -Timeout $timeoutSeconds) { $fullnamexp = Receive-Job $j }
Remove-Job -force $j
推荐答案
@mjolinor确实为您提供了一种替代方法,这里直接回答您的一般问题:如何在PowerShell中强制超时?
While @mjolinor may have indeed provided you an alternative approach, here is a direct answer to your general question: how do you force a timeout in PowerShell?
您希望在脚本块中设置时间限制,将其作为作业运行,然后使用 Wait-Job
cmdlet对操作进行时间限制。 > 。在 Wait-Job
返回后,可以检查作业状态( $ j.state
)以确定是否中断
Wrap whatever you wish to time-limit in a script block, run that as a job, then use the Wait-Job
cmdlet to time-limit the operation. Wait-Job
will return either at the end of the timeout period or when the script block completes, whichever occurs first. After Wait-Job
returns, you can examine the job state ($j.state
) to determine whether it was interrupted or not, if it matters to you.
$timeoutSeconds = 5 # set your timeout value here
$j = Start-Job -ScriptBlock {
# your commands here, e.g.
Get-Process
}
"job id = " + $j.id # report the job id as a diagnostic only
Wait-Job $j -Timeout $timeoutSeconds | out-null
if ($j.State -eq "Completed") { "done!" }
elseif ($j.State -eq "Running") { "interrupted" }
else { "???" }
Remove-Job -force $j #cleanup
这里有一个简化的方法,它还包括使用 Receive-Job
,假设您希望在stdout上生成:
Here is a bit more streamlining approach that also includes the practical step of getting information out of the script block with Receive-Job
, assuming what you want is generated on stdout:
$timeoutSeconds = 3
$code = {
# your commands here, e.g.
Get-ChildItem *.cs | select name
}
$j = Start-Job -ScriptBlock $code
if (Wait-Job $j -Timeout $timeoutSeconds) { Receive-Job $j }
Remove-Job -force $j
这篇关于向batch / powershell添加超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!