我有一个powershell代码,它接受一个数组,遍历每个元素并更新另一个服务器上的SQL数据库。
似乎陷入了以下代码
do{
try{
$cmd_update = New-Object System.Data.SqlClient.SqlCommand($sql_update,$conn_update)
$found = $cmd_update.ExecuteNonQuery()
$num_moved=$num_moved+1
$timestamp = Get-Date
Add-Content D:\Script\Output_SCHOOLS_Default_Group.log "Moving $ip, SEP version $sep_version to $group_name, $timestamp`r"
Write-host Moving $ip, SEP version $sep_version to $group_name, $timestamp
$transactionComplete = $true
}
catch{
$transactionComplete = $false
}
} until ($transactionComplete)
直到$ transactionComplete,它才会保持这种状态,这可能永远不会发生,具体取决于系统瓶颈。
如果1分钟过去且$ transactionComplete仍为假,我如何退出外观?
答案 0 :(得分:2)
您可以再引入一个条件来检查执行的总时间是否超过一分钟。
例如,
$MaxTime = new-timespan -Minutes 1
$StopWatch = [Diagnostics.StopWatch]::StartNew()
do{
try{
$cmd_update = New-Object System.Data.SqlClient.SqlCommand($sql_update,$conn_update)
$found = $cmd_update.ExecuteNonQuery()
$num_moved=$num_moved+1
$timestamp = Get-Date
Add-Content D:\Script\Output_SCHOOLS_Default_Group.log "Moving $ip, SEP version $sep_version to $group_name, $timestamp`r"
Write-host Moving $ip, SEP version $sep_version to $group_name, $timestamp
$transactionComplete = $true
}
catch{
$transactionComplete = $false
}
} until ($transactionComplete -or (-not $StopWatch.Elapsed))
答案 1 :(得分:1)
将它放在循环之前:
$start = Get-Date
并将其放在catch块的末尾:
if (((Get-Date)-$start).TotalMinutes -gt 1) {
$transactionComplete = $true
}