ForEach-Object:无法转换' System.Object []'

时间:2016-04-15 16:08:35

标签: csv powershell foreach

出于某种原因,我有一个脚本开始突然给我提问。也许一位同事修改了它,我不知道,但我需要让它再次运行。

这是导致问题的脚本:

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

如果我将$filter导出为CSV而不是$result,则// Signatures function formatAPI(): string[]; function formatAPI(name: string): string; function formatAPI(name: string, callback: (arg: string) => void): void; function formatAPI(map: { [name: string]: () => string }): void; // Implementation function formatAPI(nameOrMap?: string | { [name: string]: () => string }, callback?:(arg: string) => void): string | string[] | void { if (typeof nameOrMap === 'string') { if (callback) { return registry.register(nameOrMap, callback); } else { return registry.get(nameOrMap); } } else if (...) { // Keep adding checks here } } 包含此内容:

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

运行我的代码时出现此错误:

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

我在这个剧本中缺少什么?它需要做的只是CSV中列出的文件的搜索字符串。

1 个答案:

答案 0 :(得分:2)

$filter是一个对象列表,而不是一个scriptblock。你不能像ForEach-Object一样使用它。将您的代码更改为:

$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