Search code examples
powershellcommand-promptdirectory-tree

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


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?


Solution

  • 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.