Powershell并行: Runsapce

Powershell中要执行并行操作的话除了上一篇博客提到的Background Job以外,还可以使用Runspace的方式。

每个powershell脚本运行在一个Runspace上,使用多个Runspace相当于同时跑多个powershell脚本。

基本用法

$powershell=[powershell]::Create() #创建Runspace
$powershell.AddScript({Sleep -Seconds 10}) #添加一个可以执行的脚本

#添加参数的两种方式
$a=1
$b={param1=2,param2=3}
$powershell.AddArgument($a)
$powershell.AddParameters($b) #为多个参数赋值比较方便

#开始执行脚本,会返回一个执行对象
$asyncObj=$powershell.BeginInvoke()

#结束执行脚本,从执行对象中获取结果
$powershell.EndInvoke($asyncObj)

用Runspace并行

这里用一个数组之间赋值的应用来场景来说明下Runspace怎么用于Powershell并行。假设数组B赋值给给数组A

并行的基本方式
1. 将数组B按长度分成n份
2. 为Runspace创建一个大小为n的Runspace池(类似线程池)
3. 为池子里的Runspace分配工作,即每个Runspace负责赋一部分的值
4. 将最终结果整合

$B_size=100
$B=0..($B_size-1)
$A=@() #B copy to A


$loop_num=10
$runspace_num= 10 #threads

#脚本块

$ScriptBlock = {
   Param (
      [Object[]]$part_B
   )

   $arr=@()

   $count=$part_B.Count
   for($i=0;$i -lt $count;$i++){
        $arr+=@($part_B[$i])
   }


   return $arr
}


#创建一个资源池,指定多少个runspace可以同时执行

$RunspacePool = [RunspaceFactory]::CreateRunspacePool(1, $runspace_num)
$RunspacePool.Open()
$Jobs = @()


for($i=0;$i -lt $runspace_num;$i++){
    $delta=$B_size/$runspace_num
    $part_B=$B[($i*$delta)..(($i+1)*$delta-1)]


    $Job = [powershell]::Create().AddScript($ScriptBlock).AddArgument($part_B)
    $Job.RunspacePool = $RunspacePool
    $Jobs += New-Object PSObject -Property @{
        Pipe = $Job
        AsyncObj = $Job.BeginInvoke()
    }
}



 #循环输出等待的信息.... 直到所有的job都完成 

Write-Host "Waiting.." -NoNewline
Do {
   #Write-Host "." -NoNewline
   #Start-Sleep -Seconds 1
} While ( $Jobs.AsyncObj.IsCompleted -contains $false)
Write-Host "All jobs completed!"



#输出结果 
$Results = 0..($Throttle-1)

$Job_ID=0
ForEach ($Job in $Jobs)
{   
    $JobRes=$Job.Pipe.EndInvoke($Job.AsyncObj)

    $Results[$Job_ID]=$JobRes

    $A+=$JobRes

    #$Result=$Job.Pipe.EndInvoke($Job.AsyncObj)
    #$Results[$Job_ID] = $Result[1]

    $Job_ID++;
}

$A.Count

Runspace可以通过RunspacePool来复用Runspace,所以它可以极大地避免频繁创建删除的开销,所以效率其实是要比Background Job要更高的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Windows PowerShell 6: Essentials for Administration (IT Pro Solutions) by William Stanek English | 6 Apr. 2017 | ASIN: B06VWVJYB2 | 302 Pages | AZW3 | 647.68 KB Covers all release versions of PowerShell for all current versions of the Windows Server and Windows operating systems. Practical and precise, this hands-on guide with ready answers is designed for IT professionals working with Microsoft products, whether for on-premises, hybrid or cloud support. Inside, you'll find expert insights, tips, tricks and workarounds that will show you how to make the most of Windows PowerShell in the shortest amount of time possible. During the course of reading this book, you will master a number of complex topics, techniques, commands and functions. This book focuses on administration tasks, including: Using PowerShell to manage Windows roles and features Inventorying and evaluating computers using scripting Working with PowerShell drives, directories and files Reading and writing file contents Getting and setting security descriptors Creating access rules and taking ownership Configuring file and directory auditing Navigating the Windows Registry Creating and managing registry keys Comparing registry keys Viewing and filtering event logs Setting event log options Writing custom events Managing the state of system services Configuring service options, such as logon and recovery Joining computers to a domain Renaming computers Restarting or shutting down computers remotely Enabling or disabling system restore Creating and using checkpoints Recovering from restore points Examining running processes Analyzing computer performance Monitoring resource usage Windows PowerShell 6: Essentials for Administration can be used with the companion book, Windows PowerShell 6: IT Pro Solutions. About the Authors William Stanek Sr. was Microsoft Press's top technical author for nearly 20 years, and is widely recognized as a leading authority in Microsoft technologies. His more than 150 published works have been read by over 10 million people, translated into 34 languages, and are available in more than 70 countries. An avid outdoorsman, William enjoys hiking, spelunking, and trekking in search of adventure. So if he’s not writing or lecturing, William’s probably out enjoying the great outdoors or at the least, a backyard barbeque. William Stanek Jr. began his tech career as an intern at Stanek & Associates in 2007 and is currently working as a development and engineering lead for the company. While most high schoolers were out enjoying spring break and summer vacations, Will worked as an assistant on the publishing side of the business, before moving over to the technical side of the business during his college years at University of Washington. As a technologist, Will provided support, technical review, and made other contributions to a myriad of books written by William R. Stanek Sr. between 2010 and 2015. Since 2015 Will’s direct written contributions to over a dozen books earned him cover credits as a contributor. Will is co-author of Windows PowerShell: Essentials, IIS 10: Essentials and several other forthcoming books.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值