JonYork
JonYork

Reputation: 1243

ForEach-Object : Cannot convert 'System.Object[]'

For some reason I have a script that started to give me problems all of a sudden. Maybe a co-worker modified it, I don't know but I need to get it running again.

This is my script that is causing the problem:

$result = ForEach-Object $filter {
    Select-String -Pattern $pattern |
    Select-Object Path, LineNumber, Line }
$result | Export-Csv "W:\test\search_results\$name.csv" -NoType

This is what $filter contains if I export it to CSV rather than $result:

FullName
\\omega.dce-eir.net\etm\ETMWinHeadPROD\CRA_WEB_UA\cra_htdocs\bt\fq-eng.html
\\omega.dce-eir.net\etm\ETMWinHeadPROD\CRA_WEB_UA\cra_htdocs\bt\ll_fq-eng.html
\\omega.dce-eir.net\etm\ETMWinHeadPROD\CRA_WEB_UA\cra_htdocs\bt\menu-eng.html

I am getting this error when running my code:

ForEach-Object : Cannot convert 'System.Object[]' to the type 'System.Management.Automation.ScriptBlock' required by parameter 'Process'. Specified method is not supported.
At C:\Tools\menu.ps1:41 char:37
+             $result = ForEach-Object <<<<  $filter {
    + CategoryInfo          : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.ForEachObjectCommand

What am I missing in this script? All it needs to do, is a search string on the files listed in the CSV.

Upvotes: 0

Views: 1948

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200453

$filter is a list of objects, not a scriptblock. You can't use it like that with ForEach-Object. Change your code to this:

$filter | Select-Object -Expand FullName |
  ForEach-Object { Select-String -Path $_ -Pattern $pattern } |
  Select-Object Path, LineNumber, Line |
  Export-Csv "W:\test\search_results\$name.csv" -NoType

Upvotes: 2

Related Questions