- 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 a variable inside a Foreach-Object Parallel?
There are two different types of the variable we can use inside foreach parallel loop. One that is declared inside and the other that is declared outside of the foreach parallel loop.
Please note − We are discussing here Foreach-Object Parallel loop, featured in PowerShell version 7. For a normal foreach loop inside and outside variables are the same.
Variable declared inside the Foreach parallel loop can be used directly with its name. For example,
Example
$vms = "TestVm1","TestVM2","TestVm3" $Vms | ForEach-Object -Parallel{ $var1 = $_ Write-Output "Testing VM: $var1" }
Output
Testing VM: TestVm1 Testing VM: TestVM2 Testing VM: TestVm3
In the above example, $var1 is declared inside the foreach parallel loop and we can use it directly by its name as shown. But the below example, $log variable declared outside the foreach parallel loop we can use it inside the loop with $Using keyword followed by the variable name.
$vms = "TestVm1","TestVM2","TestVm3" $log = "Application" $Vms | ForEach-Object -Parallel{ $var1 = $_ Write-Output "Checking $($using:log) on $var1" }
Output
Checking Application on TestVm1 Checking Application on TestVM2 Checking Application on TestVm3
In the above example, $using:log variable is used inside the foreach parallel loop is a $log variable.
- Related Articles
- How to use ForEach-Object Parallel cmdlet in PowerShell?
- How to use PSCustomObject in PowerShell foreach parallel loop?
- How can I use a variable inside a Dockerfile CMD?
- How to parse array of objects inside another object using maps or forEach?
- How to use a variable for a key in a JavaScript object literal?
- PHP Casting Variable as Object type in foreach Loop
- How to declare a variable inside a procedure in MySQL?
- Parsing array of objects inside an object using maps or forEach using JavaScript?
- How to use a global variable in a Python function?
- How to use a variable in a string in jQuery?
- Calling Stored Procedure inside foreach PHP Codeigniter
- How to set an object key inside a state object in React Hooks?
- How to use PowerShell break statement in foreach loop?
- How to use the foreach loop parallelly in PowerShell?
- How to use for and foreach loop in Golang?
