
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use PSCustomObject in PowerShell ForEach Parallel Loop
To use the PSCustomObject inside the Foreach Parallel loop, we first need to consider how we are using the variables inside the loop.
$Out = "PowerShell" ForEach-Object -Parallel{ Write-Output "Hello.... $($using:Out)" }
So let see if we can store or change a value in the $out variable.
Example
$Out = @() ForEach-Object -Parallel{ $using:out = "Azure" Write-Output "Hello....$($using:out) " }
Output
Line | 4 | $using:out = "Azure" | ~~~~~~~~~~ | The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept | assignments, such as a variable or a property.
The error says that the expression is invalid so we can’t manipulate the variable directly. So we have another method that we can use a temporary variable for it.
$Out = @() ForEach-Object -Parallel{ $dict = $using:out $dict = "Azure" Write-Output "Hello....$dict" }
Similarly, we can use the PSCustomObject using the Temporary variable as shown below.
Example
$Out = @() $vms = "Testvm1","Testvm2","Testvm3" $vmout = $vms | ForEach-Object -Parallel{ $dict = $using:out $dict += [PSCustomObject]@{ VMName = $_ Location = 'EastUS' } return $dict } Write-Output "VM Output" $vmout
Output
VMName Location ------ -------- Testvm1 EastUS Testvm2 EastUS Testvm3 EastUS
Advertisements