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

Shaun Luttin picture Shaun Luttin · Apr 3, 2014 · Viewed 81.5k times · Source

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 }

Answer

Kohlbrr picture Kohlbrr · Apr 3, 2014

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