为什么这个powershell脚本不会执行

时间:2016-02-02 14:40:08

标签: windows powershell

我正在尝试创建一个执行以下操作的脚本:

  1. 打印文件
  2. 删除所有空行
  3. 过滤掉所有不包含“重新分配”字样的行
  4. 从每行的开头删除所有空格和“>”
  5. 一切正常,直到我添加第4步的函数,之后powershell吐出一堆错误。我在这里做错了什么?

    PS C:\Users\pzsr7z.000\Desktop\incidentoutput> cat .\csvtest.txt | ? {$_.trim() -ne "" } | sls "^Reassignment$" -Context 1,2 | foreach{ $_.TrimStart(">"," ")}
    Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'TrimStart'.
    At line:1 char:90
    + ... 1,2 | foreach{ $_.TrimStart(">"," ")}
    +                    ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    
    Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'TrimStart'.
    At line:1 char:90
    + ... 1,2 | foreach{ $_.TrimStart(">"," ")}
    +                    ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    
    Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'TrimStart'.
    At line:1 char:90
    + ... 1,2 | foreach{ $_.TrimStart(">"," ")}
    +                    ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    
    Method invocation failed because [Microsoft.PowerShell.Commands.MatchInfo] does not contain a method named 'TrimStart'.
    At line:1 char:90
    + ... 1,2 | foreach{ $_.TrimStart(">"," ")}
    +                    ~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : MethodNotFound
    

    所有的功能都是单独运行的,当我尝试添加最后一部分时,事情就搞砸了。

2 个答案:

答案 0 :(得分:3)

我的通灵能力告诉我,您正试图在TrimStart cmdlet返回的MatchInfo对象上使用String的{​​{3}}方法。

首先尝试将其强制转换为字符串:

... | sls "^Reassignment$" -Context 1,2 | foreach{ $_.ToString().TrimStart(">"," ")

答案 1 :(得分:1)

此正则表达式模式:^Reassignment$仅匹配具有完全Reassignment的行 - 并非所有包含 Reassignment的行

当您已经使用Get-Contentcat)来读取文件中的行时,您也可以在所有行上使用-match运算符({{1}为了区分大小写):

-cmatch

(cat .\csvtest.txt) -cmatch 'Reassignment' 运算符只返回匹配的字符串,因此您可以直接调用-match

TrimStart()