【问题标题】:Proper Syntax? Powershell error for missing parenthesis but only 6 parenthesis in command?正确的语法?缺少括号但命令中只有 6 个括号的 Powershell 错误?
【发布时间】:2017-01-15 03:40:54
【问题描述】:

Powershell 行:

 (Get-Content hist3.txt)  |  ForEach-Object { $_.split(" ",2)[0]}  |  ForEach-Object { $rgbArray = @($_)} | for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbArray[$i]}

错误消息:

在 line:1 char:114

  • ... " ",2)[0]} | ForEach 对象 {$rgbArray = @($_)} | for( $i = 0; $i -le...
  • ~ 表达式中缺少结束“)”。在 line:1 char:150
  • ... y = @($_)} | for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbAr...

  • ~ 表达式或语句中出现意外的标记 ')'。

    • CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
    • FullyQualifiedErrorId : MissingEndParenthesisInExpression

hist3.txt:

2 1388581  
3 1449812  
4 63829  
5 10477  
6 5878
7 6703  
8 105349
9 8639  
10 7270
  1. 所以我正在加载这个文本文件:(Get-Content hist3.txt)
  2. 我需要隔离每行的第一个单词:ForEach-Object { $_.split(" ",2)[0]}
  3. 将每个第一个单词保存到一个数组中:ForEach-Object { $rgbArray = @($_)}
  4. 然后遍历该数组并逐个访问每个元素:for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbArray[$i]}

我上面的代码似乎以某种方式缺少括号。或者它稍后在管道中无法识别 $rgbArray ?

您能告诉我我缺少哪些信息或需要阅读哪些信息吗?我如何让它工作?

最终目标是将元素实际加载到数组中,然后将其中的几个元素与同一数组中的其他元素进行比较。所以我会一次访问同一个数组的多个部分。

对 powershell 非常陌生,因此感谢您的帮助。

【问题讨论】:

  • 语句(如for)不能用于代替管道命令。

标签: arrays powershell syntax runtime-error pipeline


【解决方案1】:

您不能通过管道将任何内容输入forAbout For 描述它是语言命令而不是 cmdlet。

很难猜出你的最终目标。首先,依次尝试下一个代码 sn-ps 看看会发生什么:

Get-Content 'hist3.txt'

然后

Get-Content 'hist3.txt' | ForEach-Object { $_.split(" ",2)[0]}

然后

Get-Content 'hist3.txt' | ForEach-Object { $_.split(" ",2)[0]} | 
   ForEach-Object { 
        $rgbArray = @($_) 
        for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbArray[$i]}
   }

后者与next one-liner相同:

(Get-Content 'D:\PShell\Downloaded\hist3.txt.txt' )  |  ForEach-Object { $_.split(" ",2)[0]} |  ForEach-Object { $rgbArray = @($_); for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbArray[$i]}}

【讨论】:

  • 感谢您的信息。我选择这个作为答案,因为它很好地回答了我最初的问题。但是,该数组没有按我预期的那样运行。我发布了一个新问题来解释结果:stackoverflow.com/questions/41667798/…
【解决方案2】:
#you can do simply that:
Import-Csv 'hist3.txt' -Delimiter ' ' -Header Col1, Col2 | select Col1


#or this
Get-Content 'hist3.txt' | %{ ($_ -split ' ')[0]}

【讨论】:

  • 感谢您对 Import-Csv 的评论。我不知道这是可能的。我认为这很快就会对我非常有用。
猜你喜欢
  • 2013-08-24
  • 2021-05-06
  • 2015-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多