IT Questions and Answers :)

Tuesday, August 13, 2019

In the PowerShell command "Get-Process | foreach {...}", what is foreach?

In the PowerShell command "Get-Process | foreach {...}", what is foreach?

  • A built in loop construct
  • A function
  • An alias
  • A cmdlet 
In the PowerShell command "Get-Process | foreach {...}", what is foreach?

EXPLANATION


Loops are an essential construct in any programming language as they enable a block of code to be repeatedly executed. This can be useful for iterating through items in an object or repeatedly performing an operation.
This tutorial covers the five types of loops that are provided in PowerShell – namely For, ForEach, While, Do-While, and Do-Until.

ForEach Loop

The foreach statement is very useful in PowerShell when you need  to loop through an array or loop through items in an object.
ForEach allows the loop to evaluate the number a certain type of objects in an array or parent object and loop through those objects. One thing to bear in mind is that a ForEach loop is that there is a performance penalty for this convenience.
The below example,  shows a ForEach Loop operating on a object, the code assigns the  object resulting from the Get-process cmdlet to a variable, and then iterates through the  process items in the object and displays the process name.
$Processes=get-process | select-object ProcessName
$i=1
foreach ($process in $Processes)
{write-host $i "Process Name is " $process.Processname;$i++; }
Foreach can also   iterate through an array – the below code lists all the elements in an array, does a cumulative addition, and computes the total:
$testarray=10,20,30,34,54,65,657,92
$i=0
$j=0
foreach ($element in in $testarray)
{ $j=$j+$element;
Write-host  "Cumulative Amount =" $j ;
$i++ }

Share:

0 comments:

Post a Comment

Popular Posts