向批处理/ powershell添加超时

Aar*_*ron 8 powershell command-line

$fullnamexp = ((net user $winxp /domain | Select-String "Full Name") -replace "Full Name","").Trim();
Run Code Online (Sandbox Code Playgroud)

如果$winxp找不到,该命令将挂起,是否有超时我可以用它来使其在5-10秒后继续运行?不知道我会把它放在哪里.

编辑 - 我用它来提取用户名:

$reg  = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine', $tag1)
$key  = $reg.OpenSubKey('SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon')
$winxp = $key.GetValue('DefaultUserName') -replace '^.*?\\'
Run Code Online (Sandbox Code Playgroud)

$winxp然后是一个登录名,ajstepanik然后我把它放入:$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
Run Code Online (Sandbox Code Playgroud)

Mic*_*ens 15

虽然@mjolinor可能确实为您提供了另一种方法,但这里可以直接回答您的一般问题:如何在PowerShell中强制超时?

在脚本块中包装您希望限制的任何内容,将其作为作业运行,然后使用Wait-Jobcmdlet对操作进行时间限制.Wait-Job将在超时周期结束返回任一脚本块完成时,发生者为准第一.之后Wait-Job的回报,你可以检查作业状态($j.state),以确定它是否被打断或没有,如果对你很重要.

$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
Run Code Online (Sandbox Code Playgroud)

2014.01.18更新

这里有一个更简化的方法,其中还包括从脚本块中获取信息的实际步骤Receive-Job,假设您想要在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
Run Code Online (Sandbox Code Playgroud)


Rom*_*n O 5

您可以使用 Start-Sleep 来暂停脚本:

Start-Sleep -s 5
Run Code Online (Sandbox Code Playgroud)


Dan*_*n H 1

net 没有明确允许您设置其操作的超时,但您可以查看此链接以更改套接字的 ipv4 超时:

http://www.cyberciti.biz/tips/linux-increasing-or-decreasing-tcp-sockets-timeouts.html

我唯一能想象的就是产生一个工作线程,但我什至不知道这在 bash 中是否可能,我对它的了解不够流畅,无法回答这个问题;另外,它还让您面临同步问题和各种多线程问题,超出了您想要在 bash 脚本中快速完成的任务!:P