当前位置: 移动技术网 > IT编程>脚本编程>Shell > Powershell后台作业、异步操作实例

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网