簡體   English   中英

為什么不執行此Powershell腳本

[英]Why wont this powershell script execute

我正在嘗試制作執行以下操作的腳本:

  1. 打印文件
  2. 刪除任何空白行
  3. 過濾掉所有不包含單詞“ Reassignment”的行
  4. 從每行的開頭刪除所有空格和“>”

一切正常,直到我在第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

所有功能都各自獨立工作,當我嘗試添加最后一部分時,事情就搞砸了。

我的靈性告訴我,您正在嘗試對Select-String cmdlet返回的MatchInfo對象使用StringTrimStart方法。

嘗試先將其轉換為字符串:

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

此正則表達式模式: ^Reassignment$將僅匹配具有確切Reassignment -並非所有包含 Reassignment

當您已經使用Get-Contentcat )從文件中讀取-match ,也可以在所有行上使用-match運算符( -cmatch區分大小寫):

(cat .\csvtest.txt) -cmatch 'Reassignment'

-match運算符僅返回匹配的字符串,因此您可以直接在這些字符串上調用TrimStart()

$ReassignmentLines = (cat .\csvtest.txt) -cmatch 'Reassignment' |ForEach-Object {
    $_.TrimStart(">"," ")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM