正确的语法?缺少括号但命令中只有 6 个括号的 Powershell 错误?

Proper Syntax? Powershell error for missing parenthesis but only 6 parenthesis in command?

Powershell 行:

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

错误消息:

At line:1 char:114

  • ... " ",2)[0]} | ForEach-Object {$rgbArray = @($_)} | for( $i = 0; $i -le...
  • ~ Missing closing ')' in expression. At line:1 char:150
  • ... y = @($_)} | for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbAr...

  • ~ Unexpected token ')' in expression or statement.

    • 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,非常感谢您的帮助。

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

很难猜到你的最终目标。首先,按顺序尝试下一个代码片段,看看会发生什么:

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]}
   }

后者与下一个相同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]}}
#you can do simply that:
Import-Csv 'hist3.txt' -Delimiter ' ' -Header Col1, Col2 | select Col1


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