What does "%" (percent) do in PowerShell?

PowershellSyntax

Powershell Problem Overview


It seems that the % operation starts script blocks after the pipeline, although about_Script_Blocks indicates the % isn't necessary.

These all work just fine.

get-childitem | % { write-host $_.Name }

{ write-host 'hello' }

% { write-host 'hello' }

But when we add a script block after the pipeline, we need to have the % first.

get-childitem | { write-host $_.Name }

Powershell Solutions


Solution 1 - Powershell

When used in the context of a cmdlet (such as your example), it's an alias for ForEach-Object:

> Get-Alias -Definition ForEach-Object

CommandType     Name                                                Definition
-----------     ----                                                ----------
Alias           %                                                   ForEach-Object
Alias           foreach                                             ForEach-Object

When used in the context of an equation, it's the modulus operator:

> 11 % 5

1

and as the modulus operator, % can also be used in an assignment operator (%=):

> $this = 11
> $this %= 5
> $this

1

Solution 2 - Powershell

A post PowerShell - Special Characters And Tokens provides description of multiple symbols including %

% (percentage)

1. Shortcut to foreach.
Task: Print all items in a collection.
Solution.
... | % { Write-Host $_ }

2. Remainder of division, same as Mod in VB.
Example:
5 % 2

Solution 3 - Powershell

% can replace Get-ChildItem | ForEach-Object { write-host $_.Name } which will not work without either the % or the ForEach-Object.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShaun LuttinView Question on Stackoverflow
Solution 1 - PowershellKohlbrrView Answer on Stackoverflow
Solution 2 - PowershellMichael FreidgeimView Answer on Stackoverflow
Solution 3 - PowershellXaoView Answer on Stackoverflow