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

所属分类: 脚本专栏 / PowerShell 阅读数: 1432
收藏 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互斥参数使用实例

这篇文章主要介绍了Powershell互斥参数使用实例,本文给出了两个代码示例来讲解互斥参数的使用,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell实现按条件终止管道的方法

这篇文章主要介绍了PowerShell实现按条件终止管道的方法,有时你可能想在管道运行在某个特定的条件下,终止管道的运行,本文就讲解了这样一种方法,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell Continue语句使用示例

这篇文章主要介绍了PowerShell Continue语句使用示例,本文直接给出示例代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell实现动态获取当前脚本运行时消耗的内存

这篇文章主要介绍了PowerShell实现动态获取当前脚本运行时消耗的内存,本文直接给出实现脚本函数,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell实现参数互斥示例

这篇文章主要介绍了PowerShell实现参数互斥示例,本文直接给出示例代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中使用.NET将程序集加入全局程序集缓存

这篇文章主要介绍了PowerShell中使用.NET将程序集加入全局程序集缓存,本文介绍了两种方法实现把程序集加入全局程序集缓存,着重讲解了使用.Net的类库解决这个需求,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中获取当前运行脚本路径的方法

这篇文章主要介绍了PowerShell中获取当前运行脚本路径的方法,获取方法很简单,本文直接给出实现代码,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中的函数重载示例

这篇文章主要介绍了PowerShell中的函数重载示例,本文直接给出一个完整重载示例,需要的朋友可以参考下
收藏 0 赞 0 分享

PowerShell中以管理员权限启动应用程序的方法

这篇文章主要介绍了PowerShell中以管理员权限启动应用程序的方法,方法很简单,本文给出启动词本和powershell为例讲解如何用管理员身份启动软件,需要的朋友可以参考下
收藏 0 赞 0 分享
查看更多