Powershell后台作业、异步操作实例

所属分类: 脚本专栏 / PowerShell 阅读数: 1502
收藏 0 赞 0 分享

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秒。与后台作业几乎同时完成,所以后台作业更适合解决长时间执行的任务。从三个任务返回的数据观察,好处是这种按顺数在前台获得数据能减少了执行过程的开销。

更多精彩内容其他人还在看

Powershell小技巧之创建一个新对象

这篇文章主要介绍了使用Powershell简单有效的创建一个自定义对象的方法,非常的简单,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell小技巧之使用WMI工具

这篇文章主要介绍了Powershell使用WMI工具的小技巧,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell小技巧之从文件获取系统日志

事件日志对于系统管理员的重要性自不待言,而基于图形界面的事件查看器毫无疑问是我们进行日志管理的首选工具,但绝不是最快捷的工具。其实,PowerShell提供了一种更简单的方式,利用它我们不仅可访问当前系统的事件日志,而且还可对数据进行排序、格式化等等。
收藏 0 赞 0 分享

Powershell小技巧之非相同域或信任域也能远程

这篇文章主要介绍了使用Powershell在非相同域或信任域也能远程的方法以及如何设置powershell远程处理的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell小技巧之开启关闭远程连接

这篇文章主要介绍了使用Powershell开启关闭远程连接的方法,非常简单实用,有需要的朋友可以参考下
收藏 0 赞 0 分享

使用HTTP api简单的远程执行PowerShell脚本

为了你能非常简单的远程执行PoweShell脚本,使用REST API是一个很好的选择,因为现在许多流行的编程语言都可以简单的执行HTTP的GET操作。
收藏 0 赞 0 分享

Powershell小技巧之使用WS-Man来调用PowerShell命令

大多Windows系统的管理员应当已经意识到在Windows系统上进行脚本开发和命令行管理,PowerShell首当其冲。微软许多产品和一些第三方产品都提供了Windows PowerShell的管理接口。但是目前PowerShell只能运行在Windows系统上,如何才能在非W
收藏 0 赞 0 分享

Windows Powershell For 循环

这篇文章主要介绍了Windows Powershell For 循环的定义、用法以及示例,非常简单实用,有需要的朋友可以参考下
收藏 0 赞 0 分享

Windows Powershell Switch 循环

这篇文章主要介绍了Windows Powershell Switch 循环以及PowerShell中数组可以与switch语句结合,产生意想不到的效果。
收藏 0 赞 0 分享

Windows Powershell 定义函数

这篇文章主要介绍了Windows Powershell 定义函数,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多