1 回答
TA贡献1799条经验 获得超9个赞
Boe Prox多年前就此做了一篇出色的文章。他还使用PoshRSJob模块对此进行了扩展。使用这个模块可以很容易地处理这个问题。
#Create a synchronized hashtable
$sync = [hashtable]::Synchronized(@{
Time = ''
Stop = $false
Updater = ''
})
#create 5 RSJobs
1..5 | Start-RSJob -ScriptBlock {
param($sync) #accept $sync as a param
$updater = [Guid]::NewGuid() #unique id per job
while(-not $sync.Stop) { #run until told not to
$sync.Time = Get-Date
$sync.Updater = $updater
start-sleep -Seconds 1
}
} -ArgumentList $sync #pass $sync as a param
运行这个会产生 5 个工作:
Id Name State HasMoreData HasErrors Command
-- ---- ----- ----------- --------- -------
1 Job1 Running False False ...
2 Job2 Running False False ...
3 Job3 Running False False ...
4 Job4 Running False False ...
5 Job5 Running False False ...
然后您可以检查父进程中的 $sync 并看到它不断地从这些作业中更新。请注意,这些不仅仅是字符串表示,而是完整的对象。
PS C:\> $sync
Name Value
---- -----
Time 4/22/2019 11:58:35 AM
Stop False
Updater 9ab28c51-2941-4866-a064-165b1ceca673
PS C:\> $sync
Name Value
---- -----
Time 4/22/2019 11:58:37 AM
Stop False
Updater 113e78a8-1774-4cdf-9638-7235109f0a0d
终止我们设置的作业$sync.Stop = $true
PS C:\> Get-RSJob
Id Name State HasMoreData HasErrors Command
-- ---- ----- ----------- --------- -------
1 Job1 Completed False False ...
2 Job2 Completed False False ...
3 Job3 Completed False False ...
4 Job4 Completed False False ...
5 Job5 Completed False False ...
- 1 回答
- 0 关注
- 87 浏览
添加回答
举报