简体   繁体   中英

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

the Powershell line:

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

The ERROR message:

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

The hist3.txt:

2 1388581  
3 1449812  
4 63829  
5 10477  
6 5878
7 6703  
8 105349
9 8639  
10 7270
  1. So I am loading this text file : (Get-Content hist3.txt)
  2. I need to isolate the first word of each line: ForEach-Object { $_.split(" ",2)[0]}
  3. save each first word into a single array: ForEach-Object { $rgbArray = @($_)}
  4. then iterate over that array and access each element one by one : for( $i = 0; $i -le $rgbArray.length - 1; $i++ ) {$rgbArray[$i]}

my above code seems to be missing a parenthesis somehow. or maybe it doesn't recognize the $rgbArray later in the pipe?

can you tell me what information i am missing or need to read up on? How do i get this working?

the end goal is to actually load the elements into the array and then compare several of the elements to other elements in the same array. so i would be accessing multiple parts of the same array at once.

Very new to powershell so thank you for your help.

You can't pipe anything into for . About For describes that it's a language command not a cmdlet.

Hard to guess your final aim. For start, try next code snippets in sequence to see what happens:

Get-Content 'hist3.txt'

then

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

and then

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

The latter is the same as 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]}}
#you can do simply that:
Import-Csv 'hist3.txt' -Delimiter ' ' -Header Col1, Col2 | select Col1


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM