【问题标题】:Error with Out-File: Expressions are only allowed as the first element of a pipeline [closed]输出文件错误:表达式只允许作为管道的第一个元素[关闭]
【发布时间】:2015-01-02 15:26:13
【问题描述】:

以下代码行给我一个管道错误:

$user.name + "|" + $user.DisplayName | Out-File $output -Append
"Managing Group: " | + $_.name + "|" +`
" Group Description: " +  ($_.description -replace "`r`n", "  ") | Out-File $output -Append

我已尝试将部分代码替换为:

(& { process{$_.description -replace "`r`n", "  "}} )
(foeach-object{$_.description -replace "`r`n", "  "} )
%{$_.description -replace "`r`n", "  "}

但似乎没有什么能解决这个错误。

错误:

表达式只能作为管道的第一个元素。在 C:\AD-User.MonitorAll.ps1:92 字符:82 + " 组描述:" + ($_.description -replace "rn", " ")

更新:

我的问题是我错过了 |在“管理组:”之后

$user.name + "|" + $user.DisplayName | Out-File $output -Append
          "Managing Group: " + "|" + $_.name + "|" +`
            " Group Description: " +  ($_.description -replace "`r`n", "  ") | Out-File $output -Append

【问题讨论】:

  • 我拆分了代码行,因为我得到了相当长的“管理组”列表,所以我希望名称和显示名称在它自己的行上 - 仅供参考
  • 你想用|分隔符输出这个吗?如果是这样,还有更清洁的方法。
  • 是的,我正在使用 |作为分隔符
  • 是的,我刚刚做了。谢谢! :)
  • 请不要使用“更新”或“已回答”类型的文本更新标题。将问题标记为答案也有同样的目的。

标签: powershell output pipeline


【解决方案1】:

您没有在第二行引用|。此外,尽量避免使用反引号来逃避换行符。我已经重写它以使用子表达式$()

"$($user.name)|$($user.DisplayName)" | Out-File $output -Append
"Managing Group: | $($_.name)| Group Description: $($_.description -replace "`r`n", "  ")" | Out-File $output -Append

【讨论】:

  • 是的,我发现了那个错误。谢谢 :) 我对你的 $($_.name) 格式不太熟悉。另外,当您指的是带有反引号的换行符时,您的意思是何时运行代码?我被告知,反引号用于 powershell 软件中的换行符,这样长行代码更容易仅在程序中显示。
  • 子表达式 $() 像 $($user.name) 可以在字符串中使用来获取动态内容。 Powershell 将处理所有子表达式并将其替换为字符串中的结果。这样,您可以将字符串写为一部分而不是"this"+$user.name+"that"。在第二行,您使用 +'(backtick) 来拆分第二个命令,这样它就不会那么长了。反引号只是转义(忽略)脚本中隐藏的\n(换行符)。如果您在反引号后打错字并有空格,那么您的脚本将失败,因此请尽量避免使用反引号以使行更易于阅读。
【解决方案2】:

我错过了我的一个 |分隔符。谢谢@Shawn Melton。你说“|分隔符”的那一刻,我一看,意识到我有一个错字。

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 2014-05-26
    • 2014-12-01
    • 2014-09-24
    • 1970-01-01
    • 2017-06-25
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多