Run a program in a ForEach loop

Luke Quinane picture Luke Quinane · Oct 8, 2008 · Viewed 27.2k times · Source

I'm trying to get this simple PowerShell script working, but I think something is fundamentally wrong. ;-)

ls | ForEach { "C:\Working\tools\custom-tool.exe" $_ }

I basically want to get files in a directory, and pass them one by one as arguments to the custom tool.

Answer

tomasr picture tomasr · Oct 8, 2008

If you still need quotes around the command path (say, if you've got spaces), just do it like this:

ls | % { &"C:\Working\tools\custom-tool.exe" $_.FullName }

Notice the use of & before the string to force PowerShell to interpret it as a command and not a string.