- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
- Related Articles
- How to use PowerShell break statement in foreach loop?
- How to use the foreach loop parallelly in PowerShell?
- How to use ForEach-Object Parallel cmdlet in PowerShell?
- How to use for and foreach loop in Golang?
- How to check if PSCustomObject is empty in PowerShell?
- How to use a variable inside a Foreach-Object Parallel?
- foreach Loop in C#
- How to use PowerShell Break statement with the While Loop?
- How to use PowerShell break statement with the For loop?
- PHP foreach Loop.
- How do you use ‘foreach’ loop for iterating over an array in C#?
- How do we use foreach statement to loop through the elements of an array in C#?
- How does the Java “foreach” loop work?
- Using foreach loop in arrays in C#
- Iterating C# StringBuilder in a foreach loop

Advertisements