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

The% operation seems to run script blocks after the pipeline, although about_Script_Blocks indicates that% is not required.

It all works great.

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

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

 get-childitem | { write-host $_.Name } 
+56
syntax powershell
Apr 03 '14 at 19:01
source share
3 answers

When used in the context of a cmdlet (for example, your example), this is 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 is a module operator :

 > 11 % 5 1 

and as the module operator % can also be used in the assignment operator ( %= ):

 > $this = 11 > $this %= 5 > $this 1 
+85
Apr 03 '14 at 19:03
source share

PowerShell Message - Special Characters and Tokens
contains a description of several characters, 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 
+2
Dec 29 '16 at 3:18
source share

% can replace Get-ChildItem | ForEach-Object { write-host $_.Name } , and it cannot do without % or ForEach-Object

0
Jan 07 '15 at 8:59
source share



All Articles