Run arbitrary command on every item in a directory tree in PowerShell?

138 Views Asked by At

On Command Prompt I can enumerate all files in a directory tree and run an arbitrary command on all of them with either:

FOR /R %F IN (*) DO @COMMAND-HERE ARGS-HERE

Directories only:

FOR /R /D %D IN (*) DO @COMMAND-HERE ARGS-HERE

What are the equivalent commands on PowerShell?

2

There are 2 best solutions below

0
Anthony On BEST ANSWER

To iterate over all items in a folder and perform an action against them you can recursively iterate over them and with a pipe you can perform an action against that item

Get-ChildItem -Path . -Recurse | ForEach-Object { # Your command here, $_ represents each file }

And I believe you can use this for directories.

Get-ChildItem -Path . -Recurse -Directory | ForEach-Object {...}

Hope that helps.

1
lit On

All items:

Get-ChildItem -Recurse | ForEach-Object { acommand $_.FullName }

Files only:

Get-ChildItem -Recurse -File | ForEach-Object { acommand $_.FullName }

Directories only:

Get-ChildItem -Recurse -Directory | ForEach-Object { acommand $_.FullName }

This will work in Windows PowerShell 3.0+. However, Windows PowerShell 5.1 is over half a decade old. Get current and cross-platform with PowerShell Core from https://github.com/PowerShell/PowerShell