30

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.

Zoran Jankov
  • 236
  • 2
  • 5
  • 18
Luke Quinane
  • 16,447
  • 13
  • 69
  • 88

4 Answers4

46

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.

tomasr
  • 13,683
  • 3
  • 38
  • 30
  • And if flags are needed, they can be added after the end; `ls | % { &"C:\Working\tools\custom-tool.exe" $_.FullName --flag --flag2=47}` – Nick T Dec 16 '12 at 08:15
  • I found out. It's an alias for `ForEach-Object`. You can see current aliases at the powershell prompt by typing `get-alias` – User Jan 31 '13 at 16:06
37
ls | %{C:\Working\tools\custom-tool.exe $_}

As each object comes down the pipeline the tool will be run against it. Putting quotes around the command string causes it to be... a string! The local variable "$_" it then likely doesn't know what to do with so pukes with an error.

Marcel Gosselin
  • 4,610
  • 2
  • 31
  • 54
slipsec
  • 3,004
  • 3
  • 34
  • 46
6

I'm betting your tool needs the full path. The $_ is each file object that comes through the pipeline. You likely need to use an expression like this:

ls | %{C:\Working\tools\custom-tool.exe $_.fullname}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Jeffery Hicks
  • 301
  • 1
  • 5
3

Both Jeffrery Hicks and slipsec are correct. Yank the double quotes off.

$_ or $_.fullname worked in my test script (below). YMMV with your custom-tool.

gci | % { c:\windows\notepad.exe $_.fullname }

or

gci | % { c:\windows\notepad.exe $_ }
EdgeVB
  • 486
  • 2
  • 5