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

所属分类: 脚本专栏 / PowerShell 阅读数: 1534
收藏 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小技巧之查询AD用户

这篇文章主要介绍了Powershell小技巧之查询AD用户,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell小技巧之查看安装的.Net framework版本信息

本文主要介绍了使用powershell查看安装的.net framework的版本信息,非常简单使用,有需要的朋友参考下
收藏 0 赞 0 分享

Windows Azure VM上配置FTP服务器

这篇文章主要介绍了Windows Azure VM上配置FTP服务器,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell小技巧实现IE Web自动化

使用IE的COM对象来完成简单的Web自动化测试,是最小巧和廉价的Web自动化测试了,因为它不用引入第三方插件或者工具。
收藏 0 赞 0 分享

PowerShell小技巧之调用CloudFlare的SDK查询网站统计信息

本文主要是记述使用powershell调用CloudFlare的SDK查询网站统计信息,非常实用,希望对大家有所帮助
收藏 0 赞 0 分享

Powershell小技巧之判断是否包涵大小写

这篇文章主要介绍了Powershell判断是否包涵大小写的方法,需要的朋友可以参考下
收藏 0 赞 0 分享

Powershell小技巧之获取当前的时间并转换为时辰

这篇文章主要介绍了使用Powershell获取当前的时间并转换为时辰的方法,非常简单实用,有需要的朋友可以参考下
收藏 0 赞 0 分享

Windows Powershell强类型数组

强类型数组可以理解为强制数据类型的数组,也就是一个数组里只包含一种数据类型,强制转换数组语法的优势就是如果使用分号代替逗号分隔值,PowerShell将每个值看作命令文本,PowerShell会执行它并且存储结果。
收藏 0 赞 0 分享

Windows Powershell使用哈希表

哈希表(hashtable)有时候也被称为:“关联数组”或“字典”。哈希表可以称得上是计算机科学中最重要的数据结构之一,例如:在计算机操作系统、数据库系统、编译器、加密算法等计算机底层程序中,哈希表都发挥着重要的作用。
收藏 0 赞 0 分享

Windows Powershell使用管道

在Windows PowerShell中到处都会用到管道。尽管在屏幕上会看到文本,但Windows PowerShell并不通过管道在命令之间传递文本。它实际上通过管道传递对象。用于管道的表示法与其他shell中所使用的表示法十分类似,因此乍一看可能不会明显察觉到PowerShe
收藏 0 赞 0 分享
查看更多