powershell - Write to external array inside a running powershell job
问题描述
I am trying to write data to external array while running a powershell job-
This is my code sample that I' m trying-
$datafromJob = @()
$wmijobs = @()
foreach ($c in $computers) {
$wmijobs += Start-Job -Name WMIInventory -ScriptBlock {
$jobdata = get-wmiobject -ComputerName $args[0] -Class win32_computersystem -Credential $Cred -ErrorVariable Err -ErrorAction SilentlyContinue
if ($Err.length) {
Add-content -Path D:\InventoryError.log -Force -Value $Err
$details = @{
Domain = "Error"
Manufacturer = "Error"
Computer = $args[0]
Name = "Error"
}
$args[3] += New-Object PSObject -Property $details
}
if ($jobdata.length) {
$details = @{
Domain = $jobdata.Domain
Manufacturer = $jobdata.Manufacturer
Computer = $args[2]
Name = $jobdata.Name
}
$args[3] += New-Object PSObject -Property $details
}
-ArgumentList $c, $Cred, "Test", $datafromJob
}
}
Expecting Output in $datafromJob Variable, but the end of job and loop variable is empty, M not getting how it will work, anyhelp,
Do let me know if any queries on this question
解决方案
线程作业在技术上是可行的,但在您的情况下可能效果不佳。数组不是线程安全的。
$a = 1,2,3
start-threadjob { $b = $using:a; $b[0] = 2 } | receive-job -wait -auto
$a
2
2
3
嗯,从这里底部的字典集合的线程安全更新:https ://devblogs.microsoft.com/powershell/powershell-foreach-object-parallel-feature/
$threadSafeDictionary =
[System.Collections.Concurrent.ConcurrentDictionary[string,object]]::new()
Get-Process | ForEach-Object -Parallel {
$dict = $using:threadSafeDictionary
$dict.TryAdd($_.ProcessName, $_)
}
$threadSafeDictionary["pwsh"]
“并发包”:
$threadSafeArray =
[System.Collections.Concurrent.ConcurrentBag[object]]::new()
1..10 | foreach-object -parallel {
$array = $using:threadSafeArray
$array.Add($_)
}
$threadSafeArray
10
9
8
7
6
5
4
3
2
1
推荐阅读
- python - 将表格保存在 .txt 文件中
- firebase - 如何循环来自云 Firebase 集合的数据以获取用户与其他用户之间的距离
- graphql - 如何在 Micronaut GraphQL 中使用 Keycloak JWT 进行身份验证
- .htaccess - 如何保护 Shopware 中的语言商店?
- firebase - 是否可以使用 Firebase 存储将多个图像添加到 Firebase 数据库?- 颤振
- wordpress - 单击即可加载 Google 地图以符合 GDPR
- c# - 获取 Blazor 中 RenderTree 异常的组件名称或 URL
- gitlab - 如何在 Gitlab 中运行从 repo A 到管道 B 的脚本
- python - python pandas,从现有列创建一个新列,从字符串中获取xn个字符
- maven - 如何在 Maven 构建中最好地复制文件?