0

We know the % is an alias of ForEach-Object actually. But I can use such command to remove the "image" from the files name

gci | Rename-Item -NewName {$_.Name.replace("image","")}

I know it is call the ForEach-Object to implement it. How to understand this usage about omitting the character %?


And why this command cannot omit the character %

ls | Rename-Item {$_.name ($_.name -replace "image")}//error command.
2

The Get-ChildItem cmdlet gets all of the files in the current folder and then uses the pipeline operator (|) to send those files to Rename-Item.

It sends the files one-by-one, each as a separate item, so that Rename-Item also receives them one-by-one and acts upon each one in turn.

In the script block, the $_ automatic variable represents each file object as it comes to the command through the pipeline, so it can act upon it.

This behavior is very different from that of the operating system, where the first command in the pipeline produces all the output as one list, which is then passed as one block via the pipeline.

The PowerShell philosophy of pipelines has these objectives :

  • Make each program do one thing well
  • Expect the output of every program to become the input to another

This way, you may string programs, where each one does one thing well, without requiring the script to use artificial objects such as lists. Such complex objects or lists would require parsing, which PowerShell avoids by passing items instead of lists.

To conclude, ForEach-Object is not required because the concept of the PowerShell pipeline is designed specifically to avoid loops that would require it. There is no implied loop here, there are only two programs, one generating items that are handled by the next one in the pipeline.

  • Could you tell me why I cannot omit the {}? – yode Sep 24 '18 at 14:33
  • The {} on -NewName are for enclosing its operand. Is that the question? – harrymc Sep 24 '18 at 15:11
  • Where to find such usage? – yode Sep 24 '18 at 15:17
  • I just think the existance of the {} make the % disappear.. But I cannot find this usage in document – yode Sep 24 '18 at 15:19
  • 1
    For brackets see this. For the % - no it doesn't disappear, because it is just not necessary here. – harrymc Sep 24 '18 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.