Powershell后台作业、异步操作实例
2018-10-12 14:10
736 查看
Powershell是单线程程序且一次只能做一件事情。后台作业能额外增加Powershell进程在后台处理作业。当需要程序同时运行且数据量不是很大时它能很好的解决问题。但从Powershell后台回传数据是一个非常麻烦的工作,它将浪费很多时间。将会导致脚本更慢。
这里有3个并发执行任务:
$start = Get-Date
# get all hotfixes
$task1 = { Get-Hotfix }
# get all scripts in your profile
$task2 = { Get-Service | Where-Object Status -eq Running }
# parse log file
$task3 = { Get-Content -Path $env:windir\windowsupdate.log | Where-Object { $_ -like '*successfully installed*' } }
# run 2 tasks in the background, and 1 in the foreground task
$job1 = Start-Job -ScriptBlock $task1
$job2 = Start-Job -ScriptBlock $task2
$result3 = Invoke-Command -ScriptBlock $task3
# wait for the remaining tasks to complete (if not done yet)
$null = Wait-Job -Job $job1, $job2
# now they are done, get the results
$result1 = Receive-Job -Job $job1
$result2 = Receive-Job -Job $job2
# discard the jobs
Remove-Job -Job $job1, $job2
$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
上面执行全部的任务消耗了5.9秒。三个任务的结果将分别存入$result1, $result2, 和 $result3.
让我们再继续查看相继在前台执行完命令需要多长时间:
$start = Get-Date
# get all hotfixes
$task1 = { Get-Hotfix }
# get all scripts in your profile
$task2 = { Get-Service | Where-Object Status -eq Running }
# parse log file
$task3 = { Get-Content -Path $env:windir\windowsupdate.log | Where-Object { $_ -like '*successfully installed*' } }
# run them all in the foreground:
$result1 = Invoke-Command -ScriptBlock $task1
$result2 = Invoke-Command -ScriptBlock $task2
$result3 = Invoke-Command -ScriptBlock $task3
$end = Get-Date
Write-Host -ForegroundColor Red ($end - $start).TotalSeconds
结果,这次只花费了5.05秒。与后台作业几乎同时完成,所以后台作业更适合解决长时间执行的任务。从三个任务返回的数据观察,好处是这种按顺数在前台获得数据能减少了执行过程的开销。
您可能感兴趣的文章:
相关文章推荐
- 30. PowerShell -- 后台作业、异步操作实例
- Dev控件综合实例(后台数据操作,控件数据级联更新,前后台异步交互)
- 学习学习 Dev控件综合实例(后台数据操作,控件数据级联更新,前后台异步交互)
- Dev控件综合实例(后台数据操作,控件数据级联更新,前后台异步交互)
- 关于异步更新UI界面多线程执行后台操作的一些思路整理
- Ajax实现异步操作实例_针对JSON格式的请求数据
- PowerShell多线程执行前后台作业的例子
- Android Async异步操作实例---加载网络图片(慕课网笔记)
- Thinkphp——(后台栏目列表)栏目及子栏目的创建及显示实例操作
- 前端通过AJAX提交数据,后台PHP处理数据实现异步操作基本流程
- java异步操作实例
- ES6 javascript的异步操作实例详解
- 异步操作读取网络的json数据(有道翻译实例)
- c#异步操作后台运行(backgroundworker类)示例
- swing登陆程序的异步loading效果,避免程序假死状态?swing 后台操作事件长 , 界面如何显示正在等待?
- "现在已经正在使用此 SocketAsyncEventArgs 实例进行异步套接字操作"的处理
- SpringMVC后台程序接收ajax异步提交数据的实例
- linux学习入门2-3——bash命令基本操作(linuxcast.net)(bash部分快捷键、uname、history、通配符、切换用户、作业管理(前台、后台运行,暂停等操作))
- SAP后台作业记录操作
- C#实现多级子目录Zip压缩解压实例 NET4.6下的UTC时间转换 [译]ASP.NET Core Web API 中使用Oracle数据库和Dapper看这篇就够了 asp.Net Core免费开源分布式异常日志收集框架Exceptionless安装配置以及简单使用图文教程 asp.net core异步进行新增操作并且需要判断某些字段是否重复的三种解决方案 .NET Core开发日志